Search code examples
pythonformattinghex

How to format a list of int into a hex representation?


This is more a question of style and what is pythonic. I like to create a string out of a list of ids. My current code looks like that:

idL = [1, 2, 64, 32, 3200, 441122]
txt = ""
for id in idL:
    if txt != "":
        txt += "-"
    txt += "{:04X}".format(id)
print(txt)

I guess that there is a more pythonic way to do the formating. Like a generator expression.

I was also thinking if something like

txt += f"{id.hex()}"

works better - but I somehow failed to get capital letters done.

Any ideas and suggestions?


Solution

  • How about

    idL = [1, 2, 64, 32, 3200, 441122]
    txt = "-".join("{:04X}".format(id) for id in idL)
    print(txt)
    

    Edit: arguably cleaner method (credit to @Swifty)

    txt = "-".join(f"{id:04X}" for id in idL)