![]() |
VOOZH | about |
bytes() method in Python is used to create a sequence of bytes. In this article, we will check How bytes() methods works in Python.
b'geeks'
Table of Content
bytes([source[, encoding[, errors]]])
This parameter is used when the source is a string. It specifies the encoding format to convert the string into bytes. The default encoding is 'utf-8' but you can use other encodings like 'ascii', 'utf-16', etc.
Defines how to handle errors during the encoding process.
If the string contains characters from other languages, we can specify a different encoding:
b'\xff\xfe\x17\t@\t\x15\tM\t8\t'
Python String to bytes using the bytes() function, for this we take a variable with string and pass it into the bytes() function with UTF-8 parameters. When we pass a string to the bytes() method, we also need to tell Python which "language" (encoding) to use to convert the string.
b'Welcome to Geeksforgeeks'
Each number in the list must be between 0 and 255 because each byte can only hold numbers in that range. When we pass a list of numbers to the bytes() method, Python will create a bytes object where each number in the list corresponds to one byte.
b'\xd7BC'
By passing a single integer to bytes(), Python will create a bytes object of that length, filled with zero values (because a byte is initially 0).
b'\x00\x00\x00\x00\x00'