3

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!

sjakobi
  • 3,546
  • 1
  • 25
  • 43
dotancohen
  • 30,064
  • 36
  • 138
  • 197

3 Answers3

4

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))
Dek Dekku
  • 1,441
  • 11
  • 28
2

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']
gecco
  • 17,969
  • 11
  • 51
  • 68
-1
>>> 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
>>> 
melpomene
  • 84,125
  • 8
  • 85
  • 148
  • 1
    This answer adds nothing new. Dek Dekku's accepted answer already shows how to iterate over the bytes with a `for` loop. – melpomene Mar 19 '17 at 11:18
  • 1
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Donald Duck Mar 19 '17 at 11:24