# 普通字符串可以用多种方式编码成Unicode字符串,具体要看你究竟选择了哪种编码:
unicodestring = u"Hello world"
# 将Unicode转化为普通Python字符串:"encode"
utf8string = unicodestring.encode("utf-8")
asciistring = unicodestring.encode("ascii")
isostring = unicodestring.encode("ISO-8859-1")
utf16string = unicodestring.encode("utf-16")
print utf8string,type(utf8string) # 结果:Hello world <type 'str'>
print asciistring,type(asciistring) # 结果:Hello world <type 'str'>
print isostring,type(isostring) # 结果:Hello world <type 'str'>
print utf16string,type(utf16string) # 结果:��Hello world <type 'str'>
# 将普通Python字符串转化为Unicode:"decode"
plainstring1 = unicode(utf8string, "utf-8")
plainstring2 = unicode(asciistring, "ascii")
plainstring3 = unicode(isostring, "ISO-8859-1")
plainstring4 = unicode(utf16string, "utf-16")
print plainstring1,type(plainstring1) # 结果:Hello world <type 'unicode'>
print plainstring2,type(plainstring2) # 结果:Hello world <type 'unicode'>
print plainstring3,type(plainstring3) # 结果:Hello world <type 'unicode'>
print plainstring4,type(plainstring4) # 结果:Hello world <type 'unicode'>
str1 = utf8string.decode("utf-8")
str2 = asciistring.decode("ascii")
str3 = isostring.decode("ISO-8859-1")
str4 = utf16string.decode("utf-16")
print str1,type(str1) # 结果:Hello world <type 'unicode'>
print str2,type(str2) # 结果:Hello world <type 'unicode'>
print str3,type(str3) # 结果:Hello world <type 'unicode'>
print str4,type(str4) # 结果:Hello world <type 'unicode'>
# 字符串在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成其他编码。
Python---Unicode中文字符串转换成 string字符串
最新推荐文章于 2024-07-09 11:09:20 发布