by.decode(encoding='UTF-8',errors='strict')
str.encode(encoding='UTF-8',errors='strict')
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 """
5 __title__ =
6 __Time__ = 2020/2/21 15:56
7
8 """
9 # bytes转字符串方式一
10 b = b'\xe9\x80\x86\xe7\x81\xab'
11 string = str(b, 'utf-8')
12 print(string)
13
14 # bytes转字符串方式二
15 b = b'\xe9\x80\x86\xe7\x81\xab'
16 string = b.decode() # 第一参数默认utf8,第二参数默认strict
17 print(string)
18
19 # bytes转字符串方式三
20 b = b'\xe9\x80\x86\xe7\x81haha\xab'
21 string = b.decode('utf-8', 'ignore') # 忽略非法字符,用strict会抛出异常
22 print(string)
23
24 # bytes转字符串方式四
25 b = b'\xe9\x80\x86\xe7\x81haha\xab'
26 string = b.decode('utf-8', 'replace') # 用?取代非法字符
27 print(string)
28
29 # 字符串转bytes方式一
30 str1 = '逆火'
31 b = bytes(str1, encoding='utf-8')
32 print(b)
33
34 # 字符串转bytes方式二
35 b = str1.encode('utf-8')
36 print(b)
逆火
逆火
逆haha
逆�haha�
b'\xe9\x80\x86\xe7\x81\xab'
b'\xe9\x80\x86\xe7\x81\xab'