天天看點

Python-位元組總結(bytes、bytearray、方法、内置函數、子產品)bytes-不可變的位元組序列bytearray-可變的位元組序列總結

目錄

bytes-不可變的位元組序列

建立與指派

操作符

通路(序列操作符切片)

判斷子序列(成員操作符in、not in)

拼接(操作符+)

重複(操作符*)

比較(操作符==、!=、<、=<、>、>=)

删除

方法

十六進制

解碼

内置函數

子產品

bytearray-可變的位元組序列

建立

方法

添加

複制

删除

總結

bytes-不可變的位元組序列

表示 bytes 字面值的文法與字元串字面值的大緻相同,隻是添加了一個

b

字首:

  • 單引号:

    b'允許嵌入 "雙" 引号'

  • 雙引号:

    b"允許嵌入 '單' 引号"

  • 三重引号:

    b'''三重單引号'''

    ,

    b"""三重雙引号"""

建立與指派

>>> bt = b'\x01\x00\x00\x08'

>>> bt

b'\x01\x00\x00\x08'

操作符

通路(序列操作符切片)

想來在看本文之前,你已經看了python-字元串總結,切片應該已經會了,不再重複理論,直接示範。

位元組序列下标

>=0時的index 1 2 3
bytes(十六進制) 01 00 00 08
<0時的index -4 -3 -2 -1

>>> bt[0]

1

>>> bt[0:3]

b'\x01\x00\x00'

>>> bt[0:4:2]

b'\x01\x00'

>>> bt[::-1]

b'\x08\x00\x00\x01'

判斷子序列(成員操作符in、not in)

>>> b'\x00' in bt

True

>>> b'\x01' not in bt

False

拼接(操作符+)

>>> bt + b'\xff'

b'\x01\x00\x00\x08\xff'

重複(操作符*)

>>> bt * 2

b'\x01\x00\x00\x08\x01\x00\x00\x08'

比較(操作符==、!=、<、=<、>、>=)

>>> bt == bt

True

>>> bt != bt

False

>>> bt < bt[0:3] + b'\x10'

True

>>> bt <= bt

True

>>> bt > bt

False

>>> bt >= bt[0]

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

TypeError: '>=' not supported between instances of 'bytes' and 'int'

>>> bt >= bt[0:2]

True

注意,bytes類型使用切片為一個時,類型會變為int,需要轉換。

>>> type(bt[3])

<class 'int'>

>>> bt >= bytes(bt[0])

True

删除

關鍵字del, del 變量名

>>> del bt

>>> bt

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

NameError: name 'bt' is not defined

方法

對比一下字元串(删除了__*__)。

>>> dir(str)

['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']

>>> dir(bytes)

[ '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']

方法與字元串類似,隻不過參數變為了位元組

>>> b'lady_killer9'.replace(b'l',b'L')

b'Lady_kiLLer9'

其餘常見方法可檢視Python-字元串總結(建立、操作符、方法、相關内置函數、相關子產品),接下來展示不一樣的。

十六進制

fromhex(str)

此bytes類方法傳回一個解碼給定字元串的 bytes 對象。 字元串必須由表示每個位元組的兩個十六進制數位構成,其中的 ASCII 空白符會被忽略。

hex()

傳回一個字元串對象,該對象包含執行個體中每個位元組的兩個十六進制數字。

>>> bt = bytes.fromhex('01000008')

>>> bt

b'\x01\x00\x00\x08'

>>> bt.hex()

'01000008'

解碼

decode(self, /, encoding='utf-8', errors='strict')

>>> bt.decode(encoding='ascii')

'\x01\x00\x00\x08'

内置函數

class

bytes

([source[, encoding[, errors]]])

bytes 字面值中隻允許 ASCII 字元(無論源代碼聲明的編碼為何)。 任何超出 127 的二進制值必須使用相應的轉義序列形式加入 bytes 字面值。像字元串字面值一樣,bytes 字面值也可以使用

r

字首來禁用轉義序列處理。

雖然 bytes 字面值和表示法是基于 ASCII 文本的,但 bytes 對象的行為實際上更像是不可變的整數序列,序列中的每個值的大小被限制為

0 <= x < 256

(如果違反此限制将引發ValueError)。

除了字面值形式,bytes 對象還可以通過其他幾種方式來建立:

  • 指定長度的以零值填充的 bytes 對象:

    bytes(10)

  • 通過由整數組成的可疊代對象:

    bytes(range(20))

  • 通過緩沖區協定複制現有的二進制資料:

    bytes(obj)

子產品

struct

将位元組串解讀為打包的二進制資料,讀過一些協定相關的部分代碼,裡面就有這個。

bytearray-可變的位元組序列

建立

class

bytearray

([source[, encoding[, errors]]])

bytearray 對象沒有專屬的字面值文法,它們總是通過調用構造器來建立:

  • 建立一個空執行個體:

    bytearray()

  • 建立一個指定長度的以零值填充的執行個體:

    bytearray(10)

  • 通過由整數組成的可疊代對象:

    bytearray(range(20))

  • 通過緩沖區協定複制現有的二進制資料:

    bytearray(b'Hi!')

由于 bytearray 對象是可變的,還支援序列操作。與byte相同的不再重複。

方法

>>> dir(bytes)

[ '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(bytearray)

['append', 'capitalize', 'center', 'clear', 'copy', 'count', 'decode', 'endswith', 'expandtabs', 'extend', 'find', 'fromhex', 'hex', 'index', 'insert', 'isalnum', 'isalpha', 'isascii', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'pop', 'remove', 'replace', 'reverse', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

添加

append(item)

在後面添加一個對象(整數),非整數時TypeError。

>>> bt = b'01000008'

>>> bta = bytearray(bt)

>>> bta

bytearray(b'01000008')

>>> bta.append('lady_killer9')

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

TypeError: 'str' object cannot be interpreted as an integer

>>> bta.append(30)

>>> bta

bytearray(b'01000008\x1e')

extend(iterable_of_ints)

将一個全是int的可疊代對象依次添加到後面,可能效率比for循環+append要高,不然官方應該也不會加。

>>> bte = bytearray()

>>> lst = [i for i in range(65,75)]

>>> bte.extend(lst)

>>> bte

bytearray(b'ABCDEFGHIJ')

複制

copy()

傳回一個拷貝後的bytearray對象,id不同。

>>> id(bta)

1829219244656

>>> bta_copy = bta.copy()

>>> bta_copy

bytearray(b'01000008\x1e')

>>> id(bta_copy)

1829219048752

删除

pop(index=-1)。

index是索引,會删除的那個位元組,預設-1即最後一個位元組。

傳回删除的那個位元組對應的整數。

>>> bta.pop()

30

>>> bta

bytearray(b'01000008')

>>> bta.append(65)

>>> bta

bytearray(b'01000008A')

remove(value)

僅删除第一個ascii碼等于value的值,value為十進制,未找到時ValueError。

>>> bta.remove(00)

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

ValueError: value not found in bytearray

>>> bta.remove(48)

>>> bta

bytearray(b'1000008A')

>>> bta.remove(48)

>>> bta

bytearray(b'100008A')

>>> list(bta)

[49, 48, 48, 48, 48, 56, 65]

clear()

清空bytearray

>>> bta.clear()

>>> bta

bytearray(b'')

總結

bytes相比str,增加了一些方法,其餘的檢視檢視Python-字元串總結(建立、操作符、方法、相關内置函數、相關子產品)。

bytesarray相比bytes增加了一些清單的類似方法,可檢視Python-清單總結(操作符、方法、内置函數、相關子產品)。

更多python相關内容:【python總結】python學習架構梳理

本人b站賬号:lady_killer9

有問題請下方評論,轉載請注明出處,并附有原文連結,謝謝!如有侵權,請及時聯系。如果您感覺有所收獲,自願打賞,可選擇支付寶18833895206(小于),您的支援是我不斷更新的動力。