6

Possible Duplicate:
RGB Int to RGB - Python

Using Python I need to convert an int to a six digit hex that I can use as a background colour in CSS. Any ideas how to do that?

The int is a primary key of a model in Django.

Community
  • 1
  • 1
Neil
  • 8,925
  • 10
  • 44
  • 49
  • What int is that, what does it signify? Any int? Is it something random? – pcalcao Oct 04 '11 at 16:24
  • Can you give an example of the int? Is it a three int tuple? e.g. `color = (255, 255, 255)` – John Keyes Oct 04 '11 at 16:25
  • The int is a primary key of a model in Django. – Neil Oct 04 '11 at 16:25
  • This question should not have been closed. The so-called duplicate question is about converting one `int` into 3 `ints`, while this question is about converting one `int` into a `str`. – unutbu Oct 04 '11 at 18:15

2 Answers2

10

Convert an int to a 6-digit hex:

In [10]: '{0:06X}'.format(16746513)
Out[10]: 'FF8811'

Check that the hex is equivalent to the int:

In [9]: int('FF8811',16)
Out[9]: 16746513
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
5

IF you really just have an integer then "#" + hex(value) will return the appropriate code to use. However, if you have a tuple of three 0-225 integers then you need to convert the three of them to hex values, pad them if necessary and join them together. You can do this with a single string formatting operation.

hex = "#%02x%02x%02x" % (r, g, b)

The %02x means zero pad the number to two digits which the x means convert to lowercase hexidecimal. Use X if you want uppercase.

Andrew Wilkinson
  • 10,682
  • 3
  • 35
  • 38