在python 2.7中使用len获得中文字符串长度时:
>>> len('中文') 4
>>> a='你好' >>> a '\xc4\xe3\xba\xc3' >>> len(a.encode('utf-8')) Traceback (most recent call last):File "<pyshell#77>", line 1, in <module>len(a.encode('utf-8')) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in position 0: ordinal not in range(128)
在python 3.x中使用len获得中文字符串长度时:
>>> len('中文') 2
>>> a='你好' >>> a '你好' >>> len(a.encode('utf-8')) 6
从python 3开始,字符串默认均使用unicode