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'

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM