Python3最重要的进步之一就是解决了Python2中字符串与字符编码的问题。
Python2字符串的缺陷如下:
- 使用 ASCII 码作为默认编码方式,对中文处理很不友好。
- 把字符串的牵强地分为 unicode 和 str 两种类型,误导开发者
而Python3则把系统默认编码设置为了 UTF-8
>>> import sys
>>> sys.getdefaultencoding()
'utf-8'
- 1
- 2
- 3
之后,文本字符和二进制数据分别用str和bytes表示。str能表示Unicode 字符集中所有字符,而二进制字节数据则用全新的数据类型bytes表示。
str
>>> a = 'a'
>>> a
'a'
>>> type(a)
<class 'str'>
>>> b = '我'
>>> b
'我'
>>> type(b)
<class 'str'>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
bytes
Python3 中,在字符引号前加‘b’,明确表示这是一个 bytes 类型的对象,实际上它就是一组二进制字节序列组成的数据,bytes 类型可以是 ASCII范围内的字符和其它十六进制形式的字符数据,但不能用中文等非ASCII字符表示。
>>> c = b'a'
>>> c
b'a'
>>> type(c)
<class 'bytes'>
>>>
>>> d = b'\xe7\xa6\x85'
>>> d
b'\xe7\xa6\x85'
>>> type(d)
<class 'bytes'>
>>> e = b'我'
File "<stdin>", line 1
SyntaxError: bytes can only contain ASCII literal characters.
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
bytes 类型提供的操作和 str 一样,支持分片、索引、基本数值运算等操作。但是 str 与 bytes 类型的数据不能执行 + 操作,尽管在py2中是可行的。会报错:
TypeError: Can’t convert ‘bytes’ object to str implicitly
python2 与 python3 字节与字符的对应关系
Python2 | Python3 | 表现 | 转换 | 作用 |
str | bytes | 字节 | encode | 存储 |
unicode | str | 字符 | decode | 显示 |
encode 与 decode
str 与 bytes 之间的转换可以用 encode 和从decode 方法。
encode : 字符str 到 字节bytes 的编码转换,默认用UTF-8编码;
>>> s = 'Python大神'
>>> s.encode()
b'Python\xe5\xa4\xa7\xe7\xa5\x9e'
>>> s.encode('gbk')
b'Python\xb4\xf3\xc9\xf1'
- 1
- 2
- 3
- 4
- 5
decode : 字节bytes 到 字符str的转换,通用使用 UTF-8 编码格式进行转换
>>> b'Python\xe5\xa4\xa7\xe7\xa5\x9e'.decode()
'Python大神'
>>> b'Python\xb4\xf3\xc9\xf1'.decode('gbk')
'Python大神'
- 1
- 2
- 3
- 4
原文出处:
http://python.jobbole.com/88277/?utm_source=blog.jobbole.com&utm_medium=relatedPosts
扫描二维码关注公众号,回复:
1462375 查看本文章