Python String to bytes
Python String to bytes conversion can be done in two ways:
- Using bytes() constructor and passing string and encoding as argument.
- 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
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:
1 2 3 4 5 6 7 8 |
<span style="color: #008000;"><strong><code> <class 'bytes'> b'abc' Original String = abc b'xyz' Original String = xyz <img class="alignnone wp-image-28794 size-full" src="http://all-learning.com/wp-content/uploads/2018/10/python-string-to-bytes-to-string11.png" alt="python-string-to-bytes-to-string" width="1200" height="628" /> </code></strong></span> |
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