Python built-in Method - bytes()

The bytes() method is a built-in function in Python that creates an immutable bytes object from an iterable of integers in the range 0 to 255. A bytes object is similar to a bytearray, but it cannot be modified once it is created.

Here is the syntax for bytes() method:

ref‮gi:ot re‬iftidea.com
bytes(iterable)

where iterable is an iterable object containing integers in the range 0 to 255.

Here are some examples of how to use bytes():

# Create a bytes object from a list of integers
a = bytes([72, 101, 108, 108, 111])
print(a)  # Output: b'Hello'

# Create a bytes object from a string
b = bytes('hello', 'utf-8')
print(b)  # Output: b'hello'

In the first example, a list of integers representing the ASCII codes for the characters 'H', 'e', 'l', 'l', and 'o' is passed as an argument to the bytes() method, which creates a bytes object containing those values. The resulting bytes object is printed to the console, and the output shows that it contains the string 'Hello'.

In the second example, a string 'hello' is passed as an argument to the bytes() method, along with the 'utf-8' encoding parameter. The utf-8 encoding is used to convert the string to a sequence of bytes, which is then used to create the bytes object. The resulting bytes object is printed to the console, and the output shows that it contains the string 'hello'.

The bytes() method can be useful when you need to work with byte data, such as when reading and writing binary files or communicating with hardware that uses byte-oriented protocols. Since bytes objects are immutable, they cannot be modified in place, which can make them more suitable for certain applications where data integrity is critical.