Formatting hex to be printed with 2 digits?

Viewed 542

The built-in function hex() in python returns me a number in the form 0xf or 0x0 but i want them as 0x00. I found this on the python docs but dont really know how to interpret it.

Thanks

2 Answers

In python3, use this f string format:

f"0x{variable:02x}"

For maximum python2/3 compatibility, use .format():

"0x{:02x}".format(variable)
Related