How to Convert Strings to Bytes in Python

Minimal Python examples of how to convert string to bytes and vice versa.
Let’s start Python REPL and experiment.

$ python3
Python 3.7.0 (default, Jul 3 2018, 23:47:55)
[Clang 9.0.0 (clang-900.0.39.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

Convert strings to bytes
>>> data = ""
>>> type(data)
<class 'str'>
>>>
>>> data = "hello".encode()
>>> type(data)
<class 'bytes'>
>>>
>>> data = b"world"
>>> type(data)
<class 'bytes'>
Convert bytes to strings
>>> data = b"This is my bytestring"
>>> type(data)
<class 'bytes'>
>>>
>>> data = b"This is my second string".decode()
>>> type(data)
<class 'str'>
>>>
>>> data = str(b"This is my third text")
>>> type(data)
<class 'str'>

Leave a Reply