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.
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'.