Python String to bytes, bytes to String

Filed Under: Python

Python String to bytes

Python String to bytes conversion can be done in two ways:

  1. Using bytes() constructor and passing string and encoding as argument.
  2. Using encode() method on string object.

Python bytes to String

We can convert bytes to String using bytes class decode() instance method.

Let’s look at examples of converting a string to bytes and then bytes to string in a python program.


s = 'abc'

# string to bytes using bytes()
b = bytes(s, encoding='utf-8')

print(type(b))
print(b)

# bytes to string using decode()
s = b.decode()
print('Original String =', s)

s = 'xyz'

# string to bytes using encode()
b = s.encode(encoding='utf-8')
print(b)

s = b.decode()
print('Original String =', s)

Output:


<class 'bytes'>
b'abc'
Original String = abc
b'xyz'
Original String = xyz

python string to bytes, python bytes to string

Best way to convert a string to bytes

Both the ways to convert a string to bytes are perfectly fine. String encode() and decode() method provides symmetry whereas bytes() constructor is more object-oriented and readable approach. You can choose any of them based on your preference.

You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: str.encode() api doc, bytes.decode() api doc

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages