[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