Python bytes()
bytes()
returns a new "bytes" object, which is a sequence of immutable integers in the range 0<=x<256.
A byte is an immutable (non-changable) version of bytearray with the same non-mutation methods and the same indexing and slicing behavior.
If you want to have a mutable version, you can use the bytearray()
method.
Related course: Complete Python Programming Course & Exercises
bytes() syntax
bytes([source[, encoding[, errors]]])
The bytes() function can have these optional parameters:
- source (Optional) - source to initialize the array of bytes.
- encoding (Optional) - if source is a string, the encoding of the string.
- errors (Optional) - if source is a string, the action to take when the encoding conversion fails
The bytes() method returns a bytes object.
bytes() example
This way you can convert string to bytes.
string = "I like Python."
# string with encoding 'utf-8'
arr = bytes(string, 'utf-8')
print(arr)
Outputs
b`I like Python.`
When no parameters are passed, return an array of bytes with length 0
>>> b = bytes()
>>> b
b''
>>> len(b)
0
Using Python bytes()
The following example shows how to use bytes() function
# is empty
print((bytes()))
#Iterateable type
print((bytes([1,2,255])))
print(type(bytes([1,2,255])))
#string
print((bytes("Canada",'utf-8')))
#string
print((bytes("Canada",'gbk')))
# error
print((bytes([1,2,256])))
output
b''
b'\x01\x02\xff'
<class 'bytes'>
b'Canada'
File "<stdin>", line 1
print((bytes(1,2,256])))
^
SyntaxError: invalid syntax
>>>
Remember, bytes() returns immutable data
>>> x = bytes('a', 'utf-8')
>>> x
b'a'
>>> x[0] = 'b'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'bytes' object does not support item assignment
>>>