【Python 3.6.1】decode()与encode()
encode编码:str->bytes
decode解码:bytes->str
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
[root@dt xxf]# python3 Python 3.6.1 (default, Jul 2 2017, 16:09:42) [GCC 4.4.7 20120313 (Red Hat 4.4.7-18)] on linux Type "help", "copyright", "credits" or "license" for more information. # 定义一个变量,赋予一个字符串 >>> str = 'hello world!' >>> print (str) hello world! >>> # 变量的类型为str >>> type(str) <class 'str'> >>> # 将str字符串编码 >>> bstr = str.encode() >>> print (bstr) b'hello world!' >>> # 此时类型为bytes >>> type(bstr) <class 'bytes'> >>> # 再将字符串解码 >>> text = bstr.decode() >>> print (text) hello world! >>> # 又转回到字符串 >>> type(text) <class 'str'> >>> |
一、中文编码解码测试
1 |
[root@dt xxf]# vi code.py |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#!/usr/bin/env python3 str = '宇久科技' # encoding可以省略 str_utf8 = str.encode(encoding="utf-8") str_gbk = str.encode("GBK") print ("str:",str) print ("utf8:",str_utf8) print ("gbk:",str_gbk) print ('*'*80) dstr_utf8 = str_utf8.decode("UTF-8") dstr_gbk = str_gbk.decode(encoding="GBK") print ("utf8解码:",dstr_utf8) print ("gbk解码:",dstr_gbk) |
二、运行结果
1 2 3 4 5 6 7 8 |
[root@dt xxf]# python3 code.py str: 宇久科技 utf8: b'\xe5\xae\x87\xe4\xb9\x85\xe7\xa7\x91\xe6\x8a\x80' gbk: b'\xd3\xee\xbe\xc3\xbf\xc6\xbc\xbc' ******************************************************************************** utf8解码: 宇久科技 gbk解码: 宇久科技 [root@dt xxf]# |