Python 3.x : How to Convert String to Bytes

The best way to convert an String in Python 3.x to bytes is by making use of the encode() function on the String.


Example:
>>> plain_string = "This is my string"
>>> data_as_bytes = str.encode(plain_string)
>>> 
>>> print(type(data_as_bytes))
<class 'bytes'>
>>> 
>>> print(data_as_bytes)
b'This is my string'
>>> 

Reference documentation:


Python 3 String as Bytes Example

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!