python中的字符串编码问题——1.理解编码和解码问题

理解编码与解码(python2.7):
1)编码 是根据一个想要的编码名称,把一个字符串翻译为其原始字节形式。
>>> u_str=u'字符串编码aabbbcccddd'
>>> u_str
u'\u5b57\u7b26\u4e32\u7f16\u7801aabbbcccddd'
>>> type(u_str)
<type 'unicode'>
>>> len(u_str)
16
>>> encode_str=u_str.encode('utf-8') #将u_str编码utf-8,每个汉字字符分配3个字节。uhf-8中字符长度(https://blog.csdn.net/bluetjs/article/details/52936943)
>>> encode_str
'\xe5\xad\x97\xe7\xac\xa6\xe4\xb8\xb2\xe7\xbc\x96\xe7\xa0\x81aabbbcccddd'
>>> type(encode_str)
<type 'str'>
>>> print encode_str  #python默认按照UTF-8解码
字符串编码aabbbcccddd
>>> len(encode_str)
26
----------------------------------------------------------------------------------
2)解码 是根据其编码名称,把一个原始字节串翻译为字符串形式的过程。
>>> utf_str=encode_str.decode('utf-8')
>>> type(utf_str)
<type 'unicode'>
>>> utf_str
u'\u5b57\u7b26\u4e32\u7f16\u7801aabbbcccddd'
>>> print utf_str
字符串编码aabbbcccddd
>>> len(utf_str)
16
>>>

猜你喜欢

转载自www.cnblogs.com/Micang/p/9721113.html