1. encode
encode将字符串转换为bytes类型的对象 (即b为前缀, bytes类型), 即Ascll编码, 字节数组
>>> a0 = '哈哈' >>> b = a0.encode() >>> type(b) <class 'bytes'> >>> >>> b b'xe5x93x88xe5x93x88'
2. decode
字节编码可decode为str
>>> a1 = b'xe7x8ex8bxe8x80x85xe5x86x9cxe8x8dxaf' >>> b = a1.decode() >>> b '王者农药' >>> type(b) <class 'str'>
3. encode('raw_unicode_escape')和 decode('raw_unicode_escape')
若某字符串的内容为bytes形式, 如 a = 'xe7x8ex8bxe8x80x85xe5x86x9cxe8x8dxaf'
可使用encode('raw_unicode_escape')将此str转化为bytes, 再decode为str
可使用decode('raw_unicode_escape')输出内容为bytes形式的字符串
>>> a = 'xe7x8ex8bxe8x80x85xe5x86x9cxe8x8dxaf' >>> b = a.encode('raw_unicode_escape') >>> type(b) <class 'bytes'> >>> b b'xe7x8ex8bxe8x80x85xe5x86x9cxe8x8dxaf' >>> >>> b.decode() '王者农药' >>> >>> b.decode('raw_unicode_escape') 'çx8ex8bèx80x85åx86x9cèx8d¯'
4. encode('unicode-escape')和 decode('unicode-escape')
若某字符串的内容为unicode形式, 如s = 'u5403u9e21u6218u573a', 在py3中默认为utf-8编码, py3将其自动解释为 '吃鸡战场'
encode('unicode-escape')可将此str编码为bytes类型, 内容则是unicode形式
decode('unicode-escape')可将内容为unicode形式的bytes类型转换为str
>>> a = 'u5403u9e21u6218u573a' >>> b = a.encode('unicode-escape') >>> type(b) <class 'bytes'> >>> b b'\u5403\u9e21\u6218\u573a' >>> >>> b.decode('utf-8') '\u5403\u9e21\u6218\u573a' >>> >>> >>> c = b.decode('utf-8') >>> c '\u5403\u9e21\u6218\u573a' >>> >>> c.encode() b'\u5403\u9e21\u6218\u573a' >>> >>> c.encode().decode('unicode-escape') '吃鸡战场'
5. python2使用ASC11码作为默认编码方式, python3的默认编码为utf-8
Python 2.7.16 (default, Aug 24 2019, 18:37:03) [GCC 4.2.1 Compatible Apple LLVM 11.0.0 (clang-1100.0.32.4) (-macos10.15-objc-s on darwin Type "help", "copyright", "credits" or "license" for more information. >>> >>> s = u'u5403u9e21u6218u573a' >>> s u'u5403u9e21u6218u573a' Python 3.7.4 (v3.7.4:e09359112e, Jul 8 2019, 14:54:52) [Clang 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> >>> s = u'u5403u9e21u6218u573a' >>> s 吃鸡战场