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

3 comments on “Python 3 : Convert string to bytes

  1. 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

    1. 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()

Leave a Comment

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