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

python decode-encode

2016-07-14 19:33 218 查看
字符串在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 re
temp = "共同创造美好的新世纪"
#temp = temp.strip()
temp = temp.decode('utf8')
print temp[0:10]

print len(temp)
print temp[0:2]
print temp[:3].__class__

temp = re.split('[。,]'.decode('utf8'),temp)
#temp = temp.split('[。,]')
print len(temp)
for _ in temp:
#_ = _.decode('utf8')
print _
print _.__class__
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: