【PYTHON3學習】bytes和str

Python3——bytes 和str

參考鏈接

  1. Python3種的str和bytes區別、包含python2與python3的區別
  2. Python3中的bytes和str類型

編碼方式

  • ASCII編碼:8個比特位代表一個字符的編碼,最多表示282^8個字符
  • UNICODE:規定任何一個字符都用2個字節表示(包括英文),不兼容ASCII
  • UTF-8編碼:英文字符系列1字節,漢子3字節表示。兼容ASCII
  • 國產編碼:GBKGB2312BIG5

方法

>>> dir(bytes)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'center', 'count', 'decode', 'endswith', 'expandtabs', 'find', 'fromhex', 'hex', 'index', 'isalnum', 'isalpha', 'isascii', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

發現strbytes有非常相似的方法。
特別的,
str——獨有encode
bytes——獨有decode

str,bytes之間的轉換

img

str.encode(‘encoding’) -> bytes

bytes.decode(‘encoding’) -> str

#必須顯示地指定編碼格式

實例:


'''中文編碼'''
>>> a='中文'
>>> type(a)
str
>>> b=bytes(a,encoding='utf-8')
>>> b
b'\xe4\xb8\xad\xe6\x96\x87'    #變成了utf-8的編碼格式
 
'''中文解碼'''
>>> c=str(b,encoding='utf-8')
>>> type(c)
str
>>> c
'中文'                        #解碼後變成str
 
'''英文編碼,因爲英文裏,utf-8和ASCII是兼容的,所以顯示b'hello',其實也是數字'''
>>> a='hello'
>>> b=bytes(a,encoding='utf-8')
>>> b			#輸入B,編碼爲(數字),按照ascii的形式顯示
b'hello'
>>> len(b)
5
 
'''英文解碼'''
>>> a=b'hello'
>>> type(a)
bytes
>>> b=str(a,encoding='utf-8')
>>> b
'hello'

bytes與str連接

#bytes連接str
>>> a='中文'
>>> b=bytes(a,encoding='utf-8')
>>> b+=bytes('end','utf-8')
>>> b.strip('end')

未完待續

(a,encoding=‘utf-8’)

b+=bytes(‘end’,‘utf-8’)
b.strip(‘end’)


# 未完待續

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章