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 (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail:

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