[python基础] python 2与python 3之间的区别 —— 默认中文字符串长

在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

posted @ 2017-10-23 21:16  InkDie  阅读(3195)  评论(0编辑  收藏  举报