bytes in Python

bytes in Python is a binary sequence type. Here are the list of 3 binary sequence types available in Python:

  1. bytes
  2. bytearray
  3. memoryview

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:

  1. using single quotes
  2. using double quotes
  3. using three single quotes
  4. 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'

x = b"allows embedded 'single' quotes"

x = b'''three single quotes'''

x = b"""three double quotes"""

The snapshot given below shows the sample run of above Python program, demonstrating the creation of bytes in Python:

python bytes

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")

The snapshot given below shows the sample run with user input CodesCracker as string to list and print ASCII values of all characters:

bytes in python

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"

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'

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.

Python Online Test

« Previous Tutorial Next Tutorial »

Follow/Like Us on Facebook

Subscribe Us on YouTube