[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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM