In this lesson, you’ll explore the common sequence operations that bytes objects support. You’ll take a closer look at:
- The
inandnot inoperators - Concatenation (
+) and replication (*) operators - Indexing and slicing
- Built-in functions
len(),min(), andmax() - Methods for
bytesobjects bytes.fromhex(<s>)andb.hex()
For more information about hexadecimal values, check out the following resources:
Here’s how to use the in and not in operators:
>>> a = b'abcde'
>>> a
b'abcde'
>>> b'cd' in a
True
>>> b'spam' in a
False
>>> b'spam' not in a
True
Here’s how to use the concatenation (+) and replication (*) operators:
>>> a = b'abcde'
>>> a
b'abcde
>>> b = b'fghij'
>>> b
b'fghij'
>>> a + b
b'abcdefghij'
>>> a * 3
b'fghijfghijfghij'
Here’s how to do indexing and slicing:
>>> a = b'abcde'
>>> a[2]
99
>>> a[1]
98
>>> a[2:4]
b'cd'
>>> a[1:5]
b'bcde'
Here’s how to use the built-in functions len(), min(), and max():
>>> a = b'abcde'
>>> len(a)
5
>>> max(a)
101
>>> chr(101)
'e'
>>> min(a)
97
>>> chr(97)
'a'
Here’s how to use the methods for bytes objects:
>>> a = b'spam,egg,spam,bacon,spam,lobster'
>>> a
b'spam,egg,spam,bacon,spam,lobster'
>>> a.count(b'spam')
3
>>> a.count('spam')
Traceback (most recent call last):
File "<input>", line 1, in <module>
a.count('spam')
TypeError: argument should be integer or bytes-like object, not 'str'
>>> a.endswith(b'ster')
True
>>> a.find(b'bacon')
14
>>> a
b'spam,egg,spam,bacon,spam,lobster'
>>> a.split(sep=b',')
[b'spam', b'egg', b'spam', b'bacon' , b'spam', b'lobster']
>>> a.center(40, b'-')
b'----spam,egg,spam,bacon,spam,lobster----'
>>> a.center(40, ' ')
Traceback (most recent call last):
File "<input>", line 1, in <module>
a.center(40, ' ')
TypeError: center() argument 2 must be a byte string of length 1, not 'str'
Here’s how to use bytes.fromhex(<s>) and b.hex():
>>> a = b'spam,egg,spam,bacon,spam,lobster'
>>> a[1]
112
>>> a[3]
109
>>> hex(a[0])
'0x73'
>>> a[0]
115
>>> list(a)
[115, 112, 97, 109, 44, 101, 103, 103, 44, 115, 112, 97, 109, 44, 98, 97, 99, 111, 110, 44, 115, 112, 97, 109, 44, 108, 111, 98, 115, 116, 101, 114]
>>> b = bytes.fromhex(' aa 68 32 af ')
>>> b
b'\xaah2\xaf'
>>> list(b)
[170, 104, 50, 175]
>>> b
b'\xaah2\xaf'
>>> b.hex()
'aa6832af'
>>> type(b.hex())
<class 'str'>

Alain Rouleau on July 29, 2020
That
bytes.fromhex(' aa 68 32 af ')was quite the head-scratcher! And as to why the output has both an'h'and a'2'inb'\xaah2\xaf'? You know, there’s no'h'in hexadecimal and why'2'?But what appears to be happening is that hexadecimal 68 equals decimal 104 which in turn is ascii for
'h'. Plus hexidecimal 32 is decimal 50 which in turn is ascii for'2'. All pretty crazy!