timerring

The Encode and Decode in Python

January 19, 2025 · 0 min read · Page View:
Tutorial
Python | Encode | Decode
If you have any questions, feel free to comment below. And if you think it's helpful to you, just click on the ads which can support this site. Thanks!

Do you really know the encode and decode in Python?

The encode and decode in Python are used to convert between strings and bytes. That we all know that the string in the computer storage and communication in the network is in the form of byte sequence, not the unicode.

Encode #

So the encode is used to transform the string to the byte sequence. And when you call the encode function, you need to specify the encoding type, such as utf-8, gbk, gb2312, etc. And python will use the encoding type to transform every character in the string to the corresponding byte sequence.

s = "你好,世界"
encoded_s = s.encode('utf-8')
print(encoded_s)
# b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe4\xb8\x96\xe7\x95\x8c'
# the b is the prefix of the byte sequence.

Decode #

And the decode is the function of byte sequence. It transform the byte sequence to the string. And you should all use the same encoding type to transform the byte sequence to the string.

b = b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe4\xb8\x96\xe7\x95\x8c'
decoded_b = b.decode('utf-8')
print(decoded_b)
# 你好,世界

Related readings


<< prev | About the... Continue strolling The Different... | next >>

If you want to follow my updates, or have a coffee chat with me, feel free to connect with me: