/*Python Binary Sequence Types*/
The bytes and bytearray Python 3 introduced the following sequences of eight-bit
integers, with possible values from 0 to 255, in two types:
• bytes is immutable, like a tuple of bytes
• bytearray is mutable, like a list of bytes
The byte and bytearrays are used to manipulate binary data in python. These bytes
and bytearrays 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 byte 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 = [Link]('A2f7 4509')
print(hexStr)
byteString = b'\xa2\xf7E\t'
print([Link]())
bArray1 = b"XYZ"
bArray2 = [Link](b"X", b"P")
print(bArray2)
byteArray1 = b'ABBACACBBACA'
print([Link](b'AC'))
print([Link](b'CA'))
bArr = b'Mumbai,Kolkata,Delhi,Hyderabad'
partList = [Link](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'