在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
