Python - bytes与字符串的相互转化

decode和encode的区别和介绍

 by.decode(encoding='UTF-8',errors='strict') 

 str.encode(encoding='UTF-8',errors='strict') 

  • 显而易见decode是解码,encode是编码
  • 解码代表bytes类型转成str类型
  • 编码代表str类型转成bytes类型
  • 而bytes类型的数据一般在写入文件时需要用到

 

直接上代码

 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'

 

posted @ 2020-02-21 16:07  小菠萝测试笔记  阅读(11894)  评论(0编辑  收藏  举报