In this post, we will see how to convert String to bytes in Python.
There are two ways to convert String to bytes in Python.
[toc]
Using bytes() constructor
You can use bytes() constructor to convert String to bytes in Python. You need to pass string and encoding as argument.
Here is an example:
str1 = 'java2blog'; byte1 = bytes(str1, encoding='utf-8') print(byte1) print(type(byte1))
Output:
b’java2blog’
Using encode() method
You can also you string’s encode() method to convert String to byte.
str2 = 'python'; byte2 = str2.encode(encoding='utf-8') print(byte2) print(type(byte2))
Output:
b’python’
That’s all about Python String to bytes.