標籤:字串 操作 輸出 css abc 指定 array 找不到 utf-8
bytes、bytearrybytes(不可變位元組序列)bytearray(可變位元組屬組)bytes初始化
#空bytesprint(bytes()) #輸出:b‘‘#指定位元組的bytesprint(bytes(2)) #輸出:b‘\x00\x00‘#bytes(iterable_of_ints)->bytesprint(bytes([0,255])) #輸出b‘\x00\xff‘#bytes(string,encoding[,errors])->bytes等價於string.encode()print(bytes(‘abc‘,encoding=‘utf8‘)) #輸出b‘abc‘#bytes(bytes_or_buffer)->immutable copy of bytes_or_buffer從一個位元組序列或者buffer複製出一個新的不可變bytesa=b‘abcss‘b=bytes(a)print(b) #輸出:b‘abcss‘print(id(a)) #輸出:4368131856print(id(b)) #輸出:4368131856#說明以上複製並不是重新開闢一塊記憶體空間,而是同時指向這塊記憶體空間#使用b首碼定義print(b‘asd‘) #輸出:b‘asd‘print(b‘\x41\x61‘) #輸出:b‘Aa‘
bytes操作
#bytes和str類型類似,均為不可變,很多方法一樣print(b‘abcsda‘.replace(b‘a‘,b‘z‘)) #輸出:b‘zbcsdz‘print(b‘abc‘.find(b‘b‘)) #輸出:1#類方法(string必須是2個字元的16進位形式,空格被忽略)print(bytes.fromhex(‘6162 09 6a 6b00‘)) #b‘ab\tjk\x00‘#hex(),返回16進位表示的字串print(‘abc‘.encode().hex()) #輸出:616263 #索引print(b‘abcdef‘[2]) #輸出:99
bytearray初始化
#空bytearrayprint(bytearray()) #輸出:bytearray(b‘‘)#bytearry(int)指定位元組的bytearray,被0填充print(bytearray(5)) #輸出:bytearray(b‘\x00\x00\x00\x00\x00‘)#bytearray(iterable_of_ints)->bytearrayprint(bytearray([0,255])) #輸出:bytearray(b‘\x00\xff‘)#bytearray(string,encoding[,errors])->bytearray近似string.encode()print(bytearray(‘abc‘,encoding=‘utf8‘)) #輸出bytearray(b‘abc‘)#bytearray(bytes_or_buffer)->immutable copy of bytes_or_buffer從一個位元組序列或者buffer複製出一個新的可變的bytearray對象a=b‘abcss‘b=bytearray(a)print(b) #輸出:bytearray(b‘abcss‘)print(id(a)) #輸出:4368131856print(id(b)) #輸出:4362498768
bytearray操作
#和bytes類型的方法相同print(bytearray(b‘abcsda‘).replace(b‘a‘,b‘z‘)) #輸出:bytearray(b‘zbcsdz‘)print(bytearray(b‘abc‘).find(b‘b‘)) #輸出:1#類方法(string必須是2個字元的16進位形式,空格被忽略)print(bytearray.fromhex(‘6162 09 6a 6b00‘)) #bytearray(b‘ab\tjk\x00‘)#hex(),返回16進位表示的字串print(bytearray(‘abc‘.encode()).hex()) #輸出:616263#索引print(bytearray(b‘abcdef‘)[2]) #輸出:99#append(int)尾部追加一個元素b=bytearray()b.append(97)b.append(99)print(b) #輸出:bytearray(b‘ac‘)#insert(index,int)在指定索引位置插入元素b.insert(1,98)print(b) #輸出:bytearray(b‘abc‘)#extend(iterable_of_ints)將一個可迭代的整數集合追加到當前bytearraya=[65,66,67]b.extend(a)print(b) #輸出:bytearray(b‘abcABC‘)#pop(index=-1)指定索引上移除元素,預設從尾部刪除b.pop()print(b) #輸出:bytearray(b‘abcAB‘)#remove(value)找到第一個value移除,找不到拋異常b.remove(66)print(b) #輸出:bytearray(b‘abcAB‘)#reverse()翻轉b.reverse()print(b) #輸出:bytearray(b‘Acba‘)#clear()清空bytearrayb.clear()print(b) #輸出:bytearray(b‘‘)
編碼與解碼
#字串按照不同的字元編碼encode返回位元組序列bytesprint(‘abc‘.encode(encoding=‘utf8‘,errors=‘strict‘)) #輸出:b‘abc‘#位元組序列按照不同的字元集解碼decode返回字串print(b‘abc‘.decode(encoding="utf-8",errors=‘strict‘)) #輸出:abcprint(bytearray(b‘abc‘).decode(encoding="utf-8",errors=‘strict‘)) #輸出:abc
python-bytes-bytearray