[Self-study Python] Python bytes to string

Python bytes to string

Python string to bytes tutorial

In Python , all operations, uses, and built-in methods of the bytes type and string are basically the same. Therefore, we can also convert bytes to string.

Python bytes to string method

There are two main ways to convert bytes to string in Python: use the str() function to convert bytes to string and use the decode() function of bytes to convert bytes to string.

the case

bytes object to string

Use the str() function to convert a sequence of bytes into a string

print("嗨客网(www.haicoder.net)")

# 使用 str 函数,将 bytes 序列转成字符串
byteHaiCoder = b'Hello \xe5\x97\xa8\xe5\xae\xa2\xe7\xbd\x91(HaiCoder)!'
strHaiCoder = str(byteHaiCoder, 'utf-8')
print('strHaiCoder:', strHaiCoder)

After the program runs, the console output is as follows:

Please add a picture description

First, we add characters in front of the string HaiCoder b, and define a variable byteHaiCoder of bytes type. Then, use the str() function to convert the bytes variable into a string type, and specify the character encoding as utf-8.

Finally, use the print() function to print the converted string.

bytes object to string

Use the decode() function to convert the bytes sequence into a string.

print("嗨客网(www.haicoder.net)")

# 使用 decode 函数,将 bytes 序列转成字符串
byteHaiCoder = b'Hello \xe5\x97\xa8\xe5\xae\xa2\xe7\xbd\x91(HaiCoder)!'
strHaiCoder = byteHaiCoder.decode('utf-8')
print('strHaiCoder:', strHaiCoder)

After the program runs, the console output is as follows:

Please add a picture description

First, we add character b in front of the string HaiCoder, and define a variable byteHaiCoder of bytes type. Next, use the decode() function to convert the bytes variable into a string type, and specify the character encoding as utf-8.

Finally, use the print() function to print the converted string.

Python bytes to string summary

There are two methods of converting bytes to string in Python. The first is to use the str() function to convert bytes to string, and the second is to use the decode() function of bytes to convert bytes to string.

Guess you like

Origin blog.csdn.net/weixin_41384860/article/details/128624282