The Python bytes()
function returns a new array of bytes which is a immutable sequence of integers in the range 0 <= x < 256
.
Python bytes()
is the immutable version of bytearray()
method.
bytes([source[, encoding[, errors]]])
The bytes()
method as bytearray()
also takes three optional parameters.
1: First parameter is Source (optional)
Source is an optional parameter that can be used to initialize the array in a few different ways:
str.encode()
.0 <= x < 256
, which are used as the initial contents of the array.bytes()
method will create an array of size 0.2: Second parameter is Encoding (optional)
Encoding is also optional. However, it is required if the source is a string. Examle: utf-8
, ascii
etc.
3: Third parameter is Error (optional)
It is also an optional parameter. Depending on different conditions, it can have values like strict
, replace
, ignore
etc.
>>> x = bytes() #without argument
>>> print(x)
b' '
>>> x = bytes(3) #array of bytes of given integer
>>> print(x)
b'\x00\x00\x00'
>>> x = bytes([1,2,3]) #bytes() in iterable list
>>> print(x)
b'\x01\x02\x03'
>>> x = bytes('Python','utf-8') #bytes() and string
>>> print(x)
b'Python'
>>> x = bytes('Python', 'ascii')
>>> print(x)
b'Python'
Python bytes()
method throws following error when we use non-ASCII characters without any encoding and specifying the error.
>>> bytes('źebra') #without encoding
Traceback (most recent call last):
...............
bytes('źebra')
TypeError: string argument without an encoding
>>> bytes('źebra','ascii') #encoding without specifying error
Traceback (most recent call last):
............
bytes('źebra','ascii')
UnicodeEncodeError: 'ascii' codec can't encode
character '\u017a' in position 0: ordinal not in range(128)
>>> x = bytes('źebra','ascii','ignore') #specifying error
>>> print(x)
b'ebra' #ignores the non-ASCII character
>>> x = bytes('źebra','ascii','replace') #using error replace
>>> print(x)
b'?ebra'
That is all about Python bytes()
. You have learned about bytes()
with relevant examples.
Now let’s see how bytes() and bytearray() are different.
The simple and basic difference between Python bytes()
and bytearray()
is mutablility. bytes()
is immutable, whereas bytearray()
is mutable. Here is an example.
>>> arr = [1,2,3,4,5]
>>> #creating bytes from list of integers
>>> arr1 = bytes(arr)
>>> creating bytearray from list of integers
>>> arr2 = bytearray(arr)
>>> #modifying elements
>>> arr1[0] = 8
Traceback (most recent call last):
.............
arr1[0] = 8
TypeError: 'bytes' object does not support item assignment
>>> arr2[0] = 8
As you can clearly see from above example that bytes()
function doesn’t allow us to manipulate any element generated in the array of it whereas bytearray()
being mutable allows the manipulation of the array.