开发者

Convert an int to a CSS colour [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

RGB Int to RGB - Pyt开发者_如何学Gohon

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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜