Python中的字串操作和編碼Unicode詳解,pythonunicode

來源:互聯網
上載者:User

Python中的字串操作和編碼Unicode詳解,pythonunicode

本文主要給大家介紹了關於 Python中的字串操作和編碼Unicode的一些知識,下面話不多說,需要的朋友們下面來一起學習吧。

字串類型

str:Unicode字串。採用''或者r''構造的字串均為str,單引號可以用雙引號或者三引號來代替。無論用哪種方式進行制定,在Python內部儲存時沒有區別。

bytes:二進位字串。由於jpg等其他格式的檔案不能用str進行顯示,所以才用bytes來表示,bytes的每個位元組為一個0-255的數字。如果列印的時候,Python會把能夠用ASCII表示的部分顯示為ASCII,這樣方便閱讀。bytes幾乎支援除了格式化以外的所有str的方法,甚至包括了re模組

bytearray() :二進位可原地變動的字串。

utf-8編碼範圍

範圍 位元組數 儲存格式
0x0000~0x007F (0 ~ 127) 1位元組 0xxxxxxx
0x0080~0x07FF(128 ~ 2047) 2位元組 110xxxxx 10xxxxxx
0x0800~FFFF(2048 ~ 65535)  3位元組 1110xxxx 10xxxxxx 10xxxxxx
0x10000~1FFFFFF(65536 ~ 2097152) 4位元組 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
0x2000000~0x3FFFFFF 5位元組 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
0x4000000~0x7FFFFFFF)  6位元組 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx

位元組順序標記BOM

BOM是byte order marker的縮寫,

指定編碼寫入時的規則

Python在使用'utf-8'編碼寫入檔案時不會寫入BOM頭,但是如果指定編碼'utf-8-sig'則會迫使Python寫入一個BOM頭。

使用'utf-16-be'不會寫入一個BOM頭,但是採用'utf-16'則會寫入一個BOM頭。

>>> open('h.txt','w',encoding='utf-8-sig').write('aaa')3>>> open('h.txt','rb').read()b'\xef\xbb\xbfaaa'>>> open('h.txt','w',encoding='utf-16').write('bbb')3>>> open('h.txt','rb').read()b'\xff\xfeb\x00b\x00b\x00'>>> open('hh.txt','w',encoding='utf-16-be').write('ccc')3>>> open('hh.txt','rb').read()b'\x00c\x00c\x00c'>>> open('h.txt','w',encoding='utf-8').write('ddd')3>>> open('h.txt','rb').read()b'ddd'

讀取時的規則

如果指定了正確的編碼,那麼BOM會忽略,否則BOM會顯示為亂碼或者返回異常。

>>> open('h.txt','r').read()'鍩縟dd'>>> open('h.txt','r',encoding='utf-8-sig').read()'ddd'

編碼與解碼

  • chr和ord
>>> ord('中') #20013>>> chr(20013) #'中'
  • 把Unicode寫入程式碼進字串中。

       '\xhh':用2位十六進位來表示一個字元

       '\uhhhh':用4位十六進位來表示一個字元:

       '\Uhhhhhhhh':用8位十六進位來表示一個字元

       >>> s = 'py\x74h\u4e2don' #'pyth中on'

str和bytes, bytearray進行轉換

str.encode(encoding='utf-8')

bytes(s,encoding='utf-8')

bytes.decode(encoding='utf-8')

str(B, encoding='utf-8')

bytearray(string, encoding='utf-8')

bytearray(bytes)

文檔編碼聲明

Python預設使用utf-8編碼。

# -*- coding: latin-1 -*- :表示聲明文檔為latin-1編碼。

協助函數

sys.platform  #'win32'sys.getdefaultencoding() # 'utf-8'sys.byteorder  #'little's.isalnum()  #s表示字串s.isalpha()s.isdecimals.isdigit()s.isnumeric()s.isprintable()s.isspace()s.isidentifier() #如果字串可以用作變數名,那麼返回Trues.islower()s.isupper()s.istitle()

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的協助,如果有疑問大家可以留言交流。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.