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.
Table of Contents
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:
1 2 3 4 5 6 |
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.
1 2 3 4 5 6 |
str2 = 'python'; byte2 = str2.encode(encoding='utf-8') print(byte2) print(type(byte2)) |
Output:
b’python’
That’s all about Python String to bytes.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.