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成其他编码。

import zipfile
azip=zipfile.ZipFile("C:\\Users\\160505\\Downloads\\商品导出_20181127_1359.zip")
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "c:\python27\Lib\zipfile.py", line 756, in __init__
    self.fp = open(file, modeDict[mode])
IOError: [Errno 2] No such file or directory: 'C:\\Users\\160505\\Downloads\\\xe5\x95\x86\xe5\x93\x81\xe5\xaf\xbc\xe5\x87

azip=zipfile.ZipFile(u"C:\\Users\\160505\\Downloads\\商品导出_20181127_1359.zip")
for file in azip.namelist():
    print file
    
12.xlsx
��ͨ��Ʒ.xlsx
��װ��Ʒ.xlsx

for file in azip.namelist():
    print type(file)    
    print type(file.decode('gbk'))
    print type(file.decode('gbk').encode('utf-8'))
    
<type 'unicode'>
<type 'unicode'>
<type 'str'>
<type 'str'>
<type 'unicode'>
<type 'str'>
<type 'str'>

总结:中文的处理,先转化为unicode(decode编码),再进行解码(encode),基本都可以这么操作

猜你喜欢

转载自blog.csdn.net/zhouxuan623/article/details/84584389