user2928056
user2928056

Reputation: 57

Python - Printing/Reading first Element generally any element of bytes object

How can I print/reading the first element or generally any elements of bytes object?

a = b'BMv\x01\x00\x00\x00\x00'

I know that the first element is b'B'. I can read it with a[0] but it returns me the INT value 66. I know this stands for the b'B' because I get from int.from_bytes(b'B', byteorder='big') the value 66. What can I do to get b'B' instead of the INT value 66?

Upvotes: 2

Views: 2157

Answers (1)

vaultah
vaultah

Reputation: 46523

In general, slices are instances of parent types. a[:1] is a bytes object of length 1:

In [6]: a[:1]
Out[6]: b'B'

You can also convert a list of integers (all integers must be in [ 0, 255 ]) to bytes object by passing that list to the bytes constructor:

In [7]: bytes([a[0]])
Out[7]: b'B'

Upvotes: 1

Related Questions