Convert a string to bytes in Python
This post will discuss how to convert a string to bytes in Python (and vice versa).
There are two different ways to convert a string to bytes in Python:
1. Using bytes() function
The idea is to use the bytes constructor bytes(string, encoding) to get an array of bytes from a string using the specified encoding.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': s = 'Hello, World' b = bytes(s, 'utf-8') print(b) # b'Hello, World' |
To do the reverse, i.e., convert bytes to string, pass the bytes to a string constructor with the encoding used. If no encoding is specified, it uses the current default encoding used by the Unicode implementation.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': b = b'Hello, World' s = str(b, 'utf-8') print(s) # Hello, World |
2. Using encode() function
Another option is to use the str.encode function to encode a string using the specified encoding or default encoding utf-8.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': s = 'Hello, World' b = s.encode('utf-8') print(b) # b'Hello, World' |
To get a string decoded from the given bytes, you can use the bytes.decode function, which takes the encoding or uses the default encoding utf-8 when no encoding is specified.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': b = b'Hello, World' s = b.decode('utf-8') print(s) # Hello, World |
That’s all about converting a string to bytes in Python.
Also See:
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)