ab520025520025 发表于 2018-8-5 06:28:11

python中文decode和encode转码

  字符串在Python内部的表示是unicode编码,因此,在做编码转换时,通常需要以unicode作为中间编码,即先将其他编码的字符串解码(decode)成unicode,再从unicode编码(encode)成另一种编码。
  decode的作用是将其他编码的字符串转换成unicode编码,如str1.decode('gb2312'),表示将gb2312编码的字符串str1转换成unicode编码。
  encode的作用是将unicode编码转换成其他编码的字符串,如str2.encode('gb2312'),表示将unicode编码的字符串str2转换成gb2312编码。
  因此,转码的时候一定要先搞明白,字符串str是什么编码,然后decode成unicode,然后再encode成其他编码。
  转码的时候不禁要看代码本身的编码、文件的编码,还要看控制台的编码,这就是为什么同样是一段代码,在不同的系统(编码不同的)中会出现乱码的原因,如:
  我的eclipse里面代码为utf-8编码的。然后我这样写代码
  s="你好"
  s=s.decode('gb2312').encode('utf-8')
  print s
  报错:
  UnicodeDecodeError: 'gb2312' codec can't decode bytes in position 2-3: illegal multibyte sequence
  原因:因为我的文件为UTF-8编码的。所以你想用gb2312将其转成unicode是不可能的。
  所以正确的写法应当是:
  s="你好"
  print s
  s=s.decode('utf-8').encode('utf-8') 要用UTF-8来做编码
  print s
  发现打印出来的是乱码那只能说明一件事情就是我的eclipse控制台是GB2312的编码!
页: [1]
查看完整版本: python中文decode和encode转码