python字符串编码和转换
1. python内部以unicode编码存储字符串(和java类似),非unicdoe编码间转换需要经过unicode作为中间媒介2. 如果字符串本身就是unicode,那么直接encode进行转换;如果字符串是utf-8,那么先转换为unicode(即decode过程),然后在转换为gb2312(即encode过程)#!/usr/bin/env python#coding=utf-8
·
1. python内部以unicode编码存储字符串(和java类似),非unicdoe编码间转换需要经过unicode作为中间媒介
2. 如果字符串本身就是unicode,那么直接encode进行转换;如果字符串是utf-8,那么先转换为unicode(即decode过程),然后在转换为gb2312(即encode过程)
#!/usr/bin/env python
#coding=utf-8
s="中文"
if isinstance(s, unicode):
#s=u"中文"
print s.encode('gb2312')
else:
#s="中文"
print s.decode('utf-8').encode('gb2312')
3. python中的编码转换大底就是这三种编码:utf-8,unicode,gb2312
unicode -> utf-8 (or gb2312),直接encode
utf-8 (or gb2312) -> unicode ,直接decode
utf-8 -> gb2312(或gb2312 -> utf-8),先decode,再encode
更多推荐
所有评论(0)