Maison  >  Article  >  développement back-end  >  python3中bytes和string之间的互相转换

python3中bytes和string之间的互相转换

高洛峰
高洛峰original
2017-02-13 13:45:361392parcourir

前言

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') # 字符串,编码

首先来设置一个原始的字符串,

Python 3.2.3 (default, Apr 11 2012, 07:15:24) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> website = 'http://www.www.php.cn/'
>>> type(website)
<class &#39;str&#39;>
>>> website
&#39;http://www.www.php.cn/&#39;
>>>

按utf-8的方式编码,转成bytes

>>> website_bytes_utf8 = website.encode(encoding="utf-8")
>>> type(website_bytes_utf8)
<class &#39;bytes&#39;>
>>> website_bytes_utf8
b&#39;http://www.www.php.cn/&#39;
>>>

按gb2312的方式编码,转成bytes

>>> website_bytes_gb2312 = website.encode(encoding="gb2312")
>>> type(website_bytes_gb2312)
<class &#39;bytes&#39;>
>>> website_bytes_gb2312
b&#39;http://www.php.cn/&#39;
>>>

解码成string,默认不填

>>> website_string = website_bytes_utf8.decode()
>>> type(website_string)
<class &#39;str&#39;>
>>> website_string
&#39;http://www.php.cn/&#39;
>>>
>>>

解码成string,使用gb2312的方式

>>> website_string_gb2312 = website_bytes_gb2312.decode("gb2312")
>>> type(website_string_gb2312)
<class &#39;str&#39;>
>>> website_string_gb2312
&#39;http://www.php.cn/&#39;
>>>

更多python3中bytes和string之间的互相转换相关文章请关注PHP中文网!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn