by @codeexamples

How to convert a String to Bytes in Python

Home » python » How to convert a String to Bytes in Python

To convert a string to bytes we can use the encode() function in python.

Here is an example:

my_str = "How are you"
my_bytes = my_str.encode() # By default utf-8 encoding is selected

print(my_bytes)

Output:

b'How are you'

str.encode() : Returns an encoded version of the string as a bytes object.