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.

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

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

Copyright © Code2care 2023 | Privacy Policy | About Us | Contact Us | Sitemap