Convert String to Bytes in Python

  • Post category:String

If you want to convert a string to bytes, you can use encode(). Taking an encoding argument, encode() returns a bytes object. UTF-8 is the default, but you can use any encoding you like.

Let’s code it.

Step 1: Create a string

str = "This is an example of string."
print("str = ", str)
print("str type = ", type(str))

Step 2: Convert string to bytes

bytes = str.encode('utf-8')
print("bytes = ", bytes)
print("bytes type = ", type(bytes))

Step 3: Convert bytes to string

str = bytes.decode('utf-8')
print("str = ", str)
print("str type = ", type(str))

Output:

str =  This is an example of string.
str type =  <class 'str'>
bytes =  b'This is an example of string.'
bytes type =  <class 'bytes'>
str =  This is an example of string.
str type =  <class 'str'>

Free resources to learn advanced skills: AiHints and CodeAllow