How can I format an integer to a two digit hex?

If you're using python 3.6 or higher you can also use fstrings:

v = 10
s = f"0x{v:02x}"
print(s)

output:

0x0a

The syntax for the braces part is identical to string.format(), except you use the variable's name. See https://www.python.org/dev/peps/pep-0498/ for more.


You can use the format function:

>>> format(10, '02x')
'0a'

You won't need to remove the 0x part with that (like you did with the [2:])


You can use string formatting for this purpose:

>>> "0x{:02x}".format(13)
'0x0d'

>>> "0x{:02x}".format(131)
'0x83'

Edit: Your code suggests that you are trying to convert a string to a hexstring representation. There is a much easier way to do this (Python2.x):

>>> "abcd".encode("hex")
'61626364'

An alternative (that also works in Python 3.x) is the function binascii.hexlify().


htmlColor = "#%02X%02X%02X" % (red, green, blue)

Tags:

Python