Convert Python String to Bytes Object for Python Beginners – Python Tutorial

By | July 18, 2019

Converting a python string to bytes object is very simple in python 3.x. In this tutorial, we will use a simple example to show you how to do.

python string and bytes

Preliminaries

string.encode(encoding='utf-8', errors=errors)

where:

encoding: the text encoding, it can be utf-8, gbk, gb2312 et al. You can get more in here.

errors: it can be

'backslashreplace' – uses a backslash instead of the character that could not be encoded
'ignore' – ignores the characters that cannot be encoded
'namereplace' – replaces the character with a text explaining the character
'strict' – Default, raises an error on failure
'replace' – replaces the character with a questionmark
'xmlcharrefreplace' – replaces the character with an xml character

https://docs.python.org/3/library/codecs.html#standard-encodings

Create a python string

string = "tutorialexample.com"

Convert python string to bytes with utf-8

bytes1 = string.encode('utf-8')
print(type(bytes1))
for i in range(len(bytes1)):
    print(bytes1[i], end=" ")

The result is:

<class 'bytes'>
116 117 116 111 114 105 97 108 101 120 97 109 112 108 101 46 99 111 109

Convert python string to bytes with gbk

bytes2 = string.encode('gbk')
print(type(bytes2))
for i in range(len(bytes2)):
    print(bytes2[i], end=" ")

The result is:

<class 'bytes'>
116 117 116 111 114 105 97 108 101 120 97 109 112 108 101 46 99 111 109

Leave a Reply

Your email address will not be published. Required fields are marked *