python3 bytes 和 string转换

转自:http://www.jb51.net/article/105064.htm

前言

Python 3 最重要的新特性大概要算是对文本和二进制数据作了更为清晰的区分。

文本总是 Unicode,由 str 类型表示,二进制数据则由 bytes 类型表示。

Python 3 不会以任意隐式的方式混用 str 和 bytes,正是这使得两者的区分特别清晰。

你不能拼接字符串和字节包,也无法在字节包里搜索字符串(反之亦然),也不能将字符串传入参数为字节包的函数(反之亦然).

python3.0 中怎么创建 bytes 型数据

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

字符串

>>> website = 'http://www.jb51.net/'
>>> type(website)
<class 'str'>
>>> website
'http://www.jb51.net/'

utf-8 转bytes

>>> website_bytes_utf8 = website.encode(encoding="utf-8")
>>> type(website_bytes_utf8)
<class 'bytes'>
>>> website_bytes_utf8
b'http://www.jb51.net/'

解码成 string,默认不填

 

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

原文地址:https://www.cnblogs.com/Allen-rg/p/10524479.html