'Python display list of integers as uppercase hexadecimals

Let's have a list of integers like:

foo = [1, 2, 3, 127, 255]

How do I convert it to string which contains uppercase hexadecimal representation like below?

result = "Some text [0x1, 0x2, 0x3, 0x7F, 0xFF] some text"

Was trying to do one liner like:

result = f"Some text {'[{}]'.format(', '.join(hex(bar) for bar in foo))} some text"

But it comes with lowercase like:

'Some text [0x1, 0x2, 0x3, 0x7f, 0xff] some text'


Solution 1:[1]

You could use "0x" + format(bar, 'X') instead of hex(bar)

With f-strings: f"0x{bar:X}"

Solution 2:[2]

You can use formatting code X for that, which can be used with str.format or f-strings. For example:

numbers = ', '.join(f'0x{bar:X}' for bar in foo)
result = f"Some text [{numbers}] some text"

Be careful about nesting calls to str.format and f-strings inside each other, because it quickly becomes very hard to read.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 wim
Solution 2 Jasmijn