Skip to main content

Convert String To Bytes in Python

In our previous Python tutorial, you have learned how to convert string into array in Python. In this tutorial, you will learn how to convert String to Bytes using Python.

The conversion of strings to Bytes is very common due to a lot of file handling and Machine learning methods require you to convert them. The strings are human-readable and in order to become them machine-readable, they must be converted to byte objects. This conversion also enables the data to be directly stored on the disk.

Python has a build-in method bytes() and encode() to convert string into bytes. So here in this tutorial, you will learn how to use these methods to convert string to bytes.

So let’s proceed with coding:

Convert Strings to Bytes using bytes() Method

The bytes() method can be used to convert string to Bytes. The method takes parameter as string and encoding type to convert it.

Here in below example code, passing string and encoding tyep UTF-8 as parameter to convert to Bytes using bytes() method.

myString = "Webdamn programming blog." 

encodedString = bytes(myString,'UTF-8')

for bytes in encodedString:
    print(bytes, end = ' ')

Output:

87 101 98 100 97 109 110 32 112 114 111 103 114 97 109 109 105 110 103 32 98 108 111 103 4

Convert Strings to Byte using encode() Method

The encode() method can also be use to convert strings to bytes. It’s very common and recommended method for encoding strings.

Here in below example code, passing string and encoding tyep UTF-8 as parameter to convert to Bytes using encode() method.

myString = "Webdamn programming blog." 

encodedString = myString.encode(encoding = 'UTF-8')

for bytes in encodedString:
    print(bytes, end = ' ')

Output:

87 101 98 100 97 109 110 32 112 114 111 103 114 97 109 109 105 110 103 32 98 108 111 103 46