您的位置:首页 > 编程语言 > Python开发

python字符串乱码问题

2014-07-10 01:54 155 查看
字符串在python内部的表示是unicode编码。

因此,在做编码转换时,通常需要以unicode作为中间编码,即先将其他编码的字符串解码(decode)成unicode,再从unicode编码(encode)成另一种编码。

decode的作用是将其他编码的字符串转换成unicode编码,如string1.decode('utf-8'),表示将utf-8编码的字符串string1转换成unicode编码。

encode的作用是将unicode编码转换成其他编码的字符串,如string2.encode('utf-8'),表示将unicode编码的字符串string2转换成utf-8编码。



如果一个字符串已经是unicode了,再进行解码则将出错,因此通常要对其编码方式是否为unicode进行判断:

isinstance(string3, unicode) #用来判断string3是否为unicode编码

用非unicode编码形式的string3来encode也会报错。

#获得系统的默认编码
#!/usr/bin/env python
#coding=utf-8
import sys
print sys.getdefaultencoding()


#万能方法
#!/usr/bin/env python
#coding=utf-8
string4="你好"
if isinstance(string4, unicode):
print s.encode('gb2312')
else:
print s.decode('utf-8').encode('gb2312')
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: