class bytes(source=b”)
class bytes(source, encoding)
class bytes(source, encoding, errors)
bytes物件是不可變類型(bytearray則為可變類型)的序列,其元素為 0 <= x <= 256 整數
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
s = 'abcd' b = bytes(s, encoding='utf-8') print(b) # b'abcd' print(b[0]) # 97 print(b[:1]) # b'a' print(b[1]) # 98 print(b[1:2]) # b'b' print(b[1:2].decode(encoding='utf-8')) # b for i in b: # 97為a在ascii編碼中10進制表示 print(i, chr(i), bytes(chr(i), 'utf-8')) # 97 a b'a' # 98 b b'b' # 99 c b'c' # 100 d b'd' # 產生列表 print(list(map(bytes, zip(b'abcd')))) # [b'a', b'b', b'c', b'd'] print([i for i in b'abcd']) # [97, 98, 99, 100] |
int轉換bytes,bytes轉換回int
|
x = 123 v_bytes = x.to_bytes(length=4, byteorder='little', signed=False) print(type(v_bytes), v_bytes) # <class 'bytes'> b'{\x00\x00\x00' v_int = int.from_bytes(v_bytes, byteorder='little', signed=False) print(type(v_int), v_int) # <class 'int'> 123 |
bytes類別相關方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
# replace(bytes,bytes) print(b'abcd'.replace(b'c', b'x')) # b'abxd' # find(bytes) print(b'abcd'.find(b'c')) # 2 print(b'abcd'.find(b'x')) # -1 # decode() print(b'abcd'.decode(encoding='utf-8')) # abcd # classmethod fromhex(string) print(bytes.fromhex("61626364")) # b'abc' # hex([sep[, bytes_per_sep]]) # 61626364 print(b'abcd'.hex()) |