# str encode 后返回bytes,byts decode后返回str
a = '你好'
a1 = a.encode('utf-8')  # b'\xe4\xbd\xa0\xe5\xa5\xbd'
a2 = a.encode('gbk')  # b'\xc4\xe3\xba\xc3'
a1.decode('utf-8')    # 你好
a2.decode('gbk')      # 你好

a.encode('ascii')# 出错
#就是那个常见的UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)

 有时候我们得到的文件是以某种编码encode过的,当然也要用对应的编码decode,如果用了错误的编码decode,要么想上面那样编码不在那种编码表中,要么乱码,因为编码格式不一样嘛,要么还是报错,你会得到类似UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc4 in position 0: invalid continuation byte 的错误

 


python字符串 decode 和 encode
 

相关文章:

  • 2021-07-27
  • 2021-08-14
  • 2021-08-14
  • 2021-08-14
  • 2021-08-14
  • 2021-08-06
  • 2021-12-04
  • 2021-04-26
猜你喜欢
  • 2022-01-12
  • 2021-11-30
  • 2021-08-14
  • 2021-10-04
  • 2021-08-14
  • 2021-08-14
  • 2021-08-14
  • 2018-07-09
相关资源
相似解决方案