python3 bytes and string conversion

Preface

The most important new feature of Python 3 is probably a clearer distinction between text and binary data.

Text is always Unicode, represented by str type, and binary data is represented by bytes type.

Python 3 will not mix str and bytes in any implicit way. It is this that makes the distinction between the two particularly clear.

You cannot concatenate strings and byte packets, and you cannot search for strings in byte packets (or vice versa), and you cannot pass strings to functions whose parameters are byte packets (or vice versa).

How to create bytes data in python

>>> bytes([1,2,3,4,5,6,7,8,9])
>>> bytes("python", 'ascii') # 字符串,编码

String

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
>>> website = 'http://www.baidu.com/'
>>> type(website)
<class 'str'>
>>> website
'http://www.baidu.com/'

utf-8 to bytes

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
>>> website_bytes_utf8 = website.encode(encoding="utf-8")
>>> type(website_bytes_utf8)
<class 'bytes'>
>>> website_bytes_utf8
b'http://www.baidu.com/'

Decode into string, default is not filled

>>> website_string = website_bytes_utf8.decode()
>>> type(website_string)
<class 'str'>
>>> website_string
'http://www.baidu.com/'

Guess you like

Origin blog.csdn.net/sinat_38682860/article/details/108489537