Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Binary Sequence Types ใน Python: bytes, bytearray, memoryview


bytes และ bytearray ใช้จัดการข้อมูลไบนารี รองรับ buffer protocol ผ่าน memoryview ซึ่งเข้าถึงหน่วยความจำของออบเจ็กต์ไบนารีอื่นโดยไม่ต้องคัดลอก

รูปแบบ Byte Literals

  • b'This is byte with single quote'
  • b"Another set of bytes with double quotes"
  • b'''Bytes using three single quotes''' หรือ b"""Bytes using three double quotes"""

เมธอดสำคัญ

เมธอดคำอธิบาย
fromhex(string)คืน bytes object จากสตริง hex (2 หลักต่อไบต์) ข้าม whitespace
hex()คืนสตริง hex 2 หลักต่อไบต์
replace(byte, new_byte)แทนที่ไบต์
count(sub[, start[, end]])นับจำนวน substring ที่ไม่ทับซ้อน
find(sub[, start[, end]])หาตำแหน่งแรกของ substring คืน -1 ถ้าไม่พบ
partition(sep)แยกสตริงด้วย separator คืน tuple 3 ส่วน
memoryview(obj)คืน memory view object เพื่อเข้าถึง buffer ได้อย่างปลอดภัย

ตัวอย่างโค้ด

hexStr = bytes.fromhex('A2f7 4509')
print(hexStr)
byteString = b'\xa2\xf7E\t'
print(byteString.hex())
bArray1 = b"XYZ"
bArray2 = bArray1.replace(b"X", b"P")
print(bArray2)
byteArray1 = b'ABBACACBBACA'
print(byteArray1.count(b'AC'))
print(byteArray1.find(b'CA'))
bArr = b'Mumbai,Kolkata,Delhi,Hyderabad'
partList = bArr.partition(b',')
print(partList)
myByteArray = bytearray('String', 'UTF-8')
memView = memoryview(myByteArray)
print(memView[2])  # ASCII of 'r'
print(bytes(memView[1:5]))

ผลลัพธ์

b'\xa2\xf7E\t'
a2f74509
b'PYZ'
3
4
(b'Mumbai', b',', b'Kolkata,Delhi,Hyderabad')
114
b'trin'