Main Tutorials

Python 3 : Convert string to bytes

Code snippets to show you how to convert string to bytes and vice versa.

1. To convert a string to bytes.


data = ""  			#string
data = "".encode()	#bytes
data = b"" 			#bytes

2. To convert bytes to a String.


data = b""  		#bytes
data = b"".decode() #string
data = str(b"")  	#string

P.S Tested with Python 3.4.3

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Vladimir
5 years ago

Here is example where its not correct. I tried to convert str to byte
>>>chr(900&ord(b’\xFF’))
\x84′
>>> chr(900&ord(b’\xFF’)).encode()
b’\xc2\x84′

python 3.7

Mat
4 years ago
Reply to  Vladimir

you are actually trying to “b”” and to “.encode()” at de same line…

,,, ,,,,,,,,,,,,,,,
>>> chr(900&ord(b’\xFF’)).encode()

try maby to tipe:
>>>chr(900&ord(b’\xFF’))
and then :
>>> chr(900&ord(’\xFF’)).encode()

bkstorm
4 years ago
Reply to  Vladimir

yeah, I think b” and ”.encode() are not the same