I need to create a string of hex digits from a list of random integers (0-255). Each hex digit should be represented by two characters: 5 - \"05\", 16 - \"10\", etc.
Just for completeness, using the modern .format()
syntax:
>>> numbers = [1, 15, 255]
>>> ''.join('{:02X}'.format(a) for a in numbers)
'010FFF'
Similar to my other answer, except repeating the format string:
>>> numbers = [1, 15, 255]
>>> fmt = '{:02X}' * len(numbers)
>>> fmt.format(*numbers)
'010FFF'
The most recent and in my opinion preferred approach is the f-string
:
''.join(f'{i:02x}' for i in [1, 15, 255])
The old format style was the %
-syntax:
['%02x'%i for i in [1, 15, 255]]
The more modern approach is the .format
method:
['{:02x}'.format(i) for i in [1, 15, 255]]
More recently, from python 3.6 upwards we were treated to the f-string
syntax:
[f'{i:02x}' for i in [1, 15, 255]]
Note that the f'{i:02x}'
works as follows.
:
is the input or variable to format. x
indicates that the string should be hex. f'{100:02x}'
is '64'
and f'{100:02d}'
is '1001'
.02
indicates that the string should be left-filled with 0
's to length 2
. f'{100:02x}'
is '64'
and f'{100:30x}'
is ' 64'
.a = [0,1,2,3,127,200,255]
print str.join("", ("%02x" % i for i in a))
prints
000102037fc8ff
(Also note that your code will fail for integers in the range from 10 to 15.)