bytes in Python
bytes in Python is a binary sequence type. Here are the list of 3 binary sequence types available in Python:
The bytes is the core inbuilt type like bytearray, used in manipulating the binary data. Unlike bytearray, bytes objects are immutable sequences of single bytes, which are basically the arrays of octets, used for storing the data, but not the text.
Note - Bytes objects are similar to string objects. The difference is, values of bytes literals comes with a b prefix. For example: b'codes', b'codescracker dot com' etc.
Important - Only ASCII characters are allowed in bytes literals.
Creating bytes Literals in Python
A bytes literals can be created in one of the following ways:
- using single quotes
- using double quotes
- using three single quotes
- using three double quotes
The b prefix is required in all the cases.
Python bytes Example
Here is an example of bytes in Python. This program creates bytes objects using all the ways as given above. This program creates bytes object, and print the value, along with type using the type() method:
x = b'allows embedded "double" quotes' print(x) print(type(x)) x = b"allows embedded 'single' quotes" print(x) print(type(x)) x = b'''three single quotes''' print(x) print(type(x)) x = b"""three double quotes""" print(x) print(type(x))
The snapshot given below shows the sample run of above Python program, demonstrating the creation of bytes in Python:
ASCII Code Representing the Character of a bytes Object in Python
This program is created to receive a string input from user at run-time of the program to print the ASCII code corresponding to all the characters available in the given string:
print("Enter the String: ", end="") s = input() s = bytes(s, "utf-8") print(list(s))
The snapshot given below shows the sample run with user input CodesCracker as string to list and print ASCII values of all characters:
Python bytes Object Slicing
Just like list, bytes object can also be sliced to get some part of the bytes object value. Here is an example of bytes slicing.
x = b"python programming" print(x) print(x[0:]) print(x[-18:]) print(x[0:6]) print(x[7:14])
The 0th index refers to the index of very first element. Adding minus (-) sign before the index, refers to the native/backward indexing. That is, -1 refers to the index of very first element from last, whereas -18 refers to the 18th element's index from last. The output produced by above program would be:
b'python programming' b'python programming' b'python programming' b'python' b'program'
Note - For detail about slicing, refer to the separate tutorial of list. There you'll get all the detail.
To convert bytes object to a string object, refer to Python bytes to String program article.
« Previous Tutorial Next Tutorial »
Follow/Like Us on Facebook
Subscribe Us on YouTube