Python Binary Sequence Types


The byte and bytearrays are used to manipulate binary data in python. These bytes and bytearrys are supported by buffer protocol, named memoryview. The memoryview can access the memory of other binary object without copying the actual data.

The byte literals can be formed by these options.

  • b‘This is bytea with single quote’

  • b“Another set of bytes with double quotes”

  • b‘’’Bytes using three single quotes’’’ or b“””Bytes using three double quotes”””

Some of the methods related to byte and bytearrays are −

Method fromhex(string)

The fromhex() method returns byte object. It takes a string where each byte is containing two hexadecimal digits. In this case the ASCII whitespaces will be ignored.

Method hex()

The hex() method is used to return two hexadecimal digits from each bytes.

Method replace(byte, new_byte)

The replace() method is used to replace the byte with new byte.

Method count(sub[, start[, end]])

This function returns the non-overlapping occurrences of the substring. It will check in between start and end.

Method find(sub[, start[, end]])

The find() method can find the first occurrence of the substring. If the search is successful, it will return the index, otherwise, it will return -1.

Method partition(sep)

The Partition method is used to separate the string by using a separator. It will create a list of different partitions.

Method memoryview(obj)

The memoryview() method is used to return memory view object of given argument. The memory view is the safe way to express the Python buffer protocol. It allows to access the internal buffer of an object.

Example Code

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]))

Output

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

Updated on: 30-Jul-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements