I practiced another CodeWar problem today: RGB To Hex Conversion

To put it simply, the problem is to convert RGB numbers to hexadecimal and output them.

1
2
3
4
rgb(255, 255, 255) # returns FFFFFF
rgb(255, 255, 300) # returns FFFFFF
rgb(0,0,0) # returns 000000
rgb(148, 0, 211) # returns 9400D3

If you convert directly with hex, you get an extra “0x” and “00” becomes “0”. I wondered if there was a function like sprintf, and found this site: String formatting like C’s sprintf

Surprisingly, if you specify the format, the number is converted directly! You can also specify the number of digits.

Here is my answer:

1
2
3
4
5
def limit(a):
    return min(max(a, 0), 255)

def rgb(r, g, b):        
    return  "%02X%02X%02X" % (limit(r), limit(g), limit(b),)

So convenient~