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.isdecimal
s.isdigit()
s.isnumeric()
s.isprintable()
s.isspace()
s.isidentifier()                #如果字符串可以用作變量名,那么返回True
s.islower()
s.isupper()
s.istitle()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM