Reputation: 31501
Considering that the bytes
type is not necessarily a string, how can one see the actual bytes (ones and zeros, or octal/hexadecimal representation of such) of a bytes
object? Trying to print()
or pprint()
such an object results in printing the string representation of the object (assuming some encoding, probably ASCII or UTF-8) preceded by the b
character to indicate that the datatype is in fact bytes:
$ python3
Python 3.2.3 (default, Oct 19 2012, 19:53:16)
>>> from pprint import pprint
>>> s = 'hi'
>>> print(str(type(s)))
<class 'str'>
>>> se = s.encode('utf-8')
>>> print(str(type(se)))
<class 'bytes'>
>>> print(se)
b'hi'
>>> pprint(se)
b'hi'
>>>
Note that I am specifically referring to Python 3. Thanks!
Upvotes: 3
Views: 12660
Reputation: 9
>>> s = b'hi'
>>> s
b'hi'
>>> print(s)
b'hi'
>>> for i in s:
print(i)
104
105
>>> y = 'hi'
>>> for i in y:
print(i)
h
i
>>>
Upvotes: -1
Reputation: 18850
Use Python string formatting to show the hexadecimal values of your bytes:
>>> se = b'hi'
>>> ["{0:0>2X}".format(b) for b in se]
['68', '69']
Upvotes: 2
Reputation: 1461
Use bin
, oct
or hex
and access the byte using bracket notation:
>>> print(hex(se[0]))
0x68
>>> print(hex(se[1]))
0x69
Obviously a cycle will be better:
for a_byte in se:
print (bin(a_byte))
Upvotes: 4