Python2與python3中字串的區別

來源:互聯網
上載者:User

標籤:技術分享   range   inf   分享圖片   center   pytho   size   enter   使用   

Python2

在python中包含兩種字串類型:str和unicode,str並不是完全意義上的字串,其實是由unicode經過編碼(encode)後的位元組組成的位元組字串,而unicode則是真正意義上的字串,由字元組成。

python 在內部使用兩個位元組來儲存一個unicode,使用unicode對象而不是str的好處,就是unicode方便於跨平台。

兩種方式定義一個unicode:

u1 = u‘你好‘u2 = unicode(‘你好‘, ‘utf-8‘)

 

 

str.decode方法和unicode.encode方法是最常用的:

要明白要處理的是str還是unicode, 使用對的處理方法(str.decode/unicode.encode)

Python2的預設編碼(預設字元集)是 asscii

 注意

str也能編碼(encode),unicode也能解碼(decode)unicode解碼意義不大
str編碼通常會報錯:

代碼報錯,提示錯誤資訊:UnicodeDecodeError: ‘ascii‘ codec can‘t decode byte 0xe4 in position 0: ordinal not in range(128)

是因為沒有指定defaultencoding,其實s.encode(‘utf-8’)是存在在一次隱式的decode:

預設編碼:ascii是許多報錯的原因,所以可以在代碼設定預設編碼(defaultencoding):

 

 

 

 Python3

Python3的預設編碼(預設字元集)是 utf-8

 

python3預設使用的是str類型對字串編碼,預設使用bytes操作位元據流,編碼使用enocde, 解碼使用的是decode

 

Python2與python3字串差異比較

  位元組碼 字串 預設編碼
Python2 str unicode ascii
Python3 bytes str utf-8

Python2與python3中字串的區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.