-1

Here's a simple example:

In [155]: exampleArray = bytearray([0xc0, 0xff, 0x01])
In [156]: exampleArray
Out[156]: bytearray(b'\xc0\xff\x01')
In [157]: print ' 0x'.join('{:02x}'.format(x) for x in exampleArray)
c0 0xff 0x01

but what I want is 0xc0 0xff 0x01

Willem Van Onsem
  • 397,926
  • 29
  • 362
  • 485
James Paul Mason
  • 971
  • 1
  • 12
  • 26

2 Answers2

3

As you can read in the documentation of str.join:

Return a string which is the concatenation of the strings in the iterable iterable. A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method.

So the ' 0x' is a separator that is put between the strings. You can however easily solve this with:

print ' '.join('0x{:02x}'.format(x) for x in exampleArray)
Willem Van Onsem
  • 397,926
  • 29
  • 362
  • 485
3

str.join() only places the joiner between the joined elements. From the str.join() documentation:

The separator between elements is the string providing this method.

(Bold emphasis mine).

Join on a space instead, and change the format to include the 0x prefix:

' '.join('{:#04x}'.format(x) for x in exampleArray)

The # changes the format to include the 0x prefix for you; do take into account that you need to adjust the field width to take the extra 2 characters into account (each field now takes up 4 characters, including the 0x prefix).

Demo:

>>> exampleArray = bytearray([0xc0, 0xff, 0x01])
>>> print ' '.join('{:#04x}'.format(x) for x in exampleArray)
0xc0 0xff 0x01
Martijn Pieters
  • 963,270
  • 265
  • 3,804
  • 3,187