Python bytes() Function
Returns an array of the specified number of bytes, initialized to 0. If a string is passed instead of a number, the string is encoded as bytes with the encoding (required parameter when converting strings to bytes).
Syntax
Python
Copy Code
bytes() bytes(iterable_of_ints) bytes(string, encoding[, errors]) bytes(bytes_or_buffer) bytes(size)
If no parameters are passed, an empty bytes
object is returned.
Parameters
Parameter | Description |
---|---|
iterable_of_ints |
Optional. An iterable object containing integers used to populate the bytes object |
string |
Optional. A string used to populate the bytes object. If supplied then encoding must also be supplied. |
encoding |
Optional. The encoding of the string. Required if source is a string. Typical values are ‘ascii’, ‘utf-8’, or ‘windows-1252’. See the codecs module for more. |
error |
Optional. The manner in which to handle errors. See the
codecs module for more information. All encoders implement, at the least,
|
bytes_or_buffer |
Optional. A buffer containing bytes used to populate bytes object. |
size |
Optional. The size of the bytes object to create. The bytes object will be initialised with 0's. |
Example
Python
Copy Code
myBytes = bytes(4) print(f'length of myBytes = {len(myBytes)}') print(myBytes) myBytes = bytes("Sally", "utf-16") print(f'"Sally" encoded as encoded as utf-16 bytes: {myBytes}')
Output
length of myBytes = 4 b'\x00\x00\x00\x00' "Sally" encoded as encoded as utf-16 bytes: b'\xff\xfeS\x00a\x00l\x00l\x00y\x00'