Formatting strings for hexadecimal colors in Python

I changed the function from PHP to return the color gradient (http://www.herethere.net/~samson/php/color_gradient/color_gradient_generator.php.txt). I am having trouble returning hexadecimal color codes ending in 0. This is a function:

def _get_color(current_step=0, start='000000', end='ffffff', max_steps=16): ''' Returns the color code for current_step between start and end ''' start = '{0:#x}'.format(int(start, 16)) end = '{0:#x}'.format(int(end, 16)) if int(max_steps) > 0 & int(max_steps) < 256: max_steps = max_steps else: max_steps = 16 r0 = (int(start, 16) & 0xff0000) >> 16 g0 = (int(start, 16) & 0x00ff00) >> 8 b0 = (int(start, 16) & 0x0000ff) >> 0 r1 = (int(end, 16) & 0xff0000) >> 16 g1 = (int(end, 16) & 0x00ff00) >> 8 b1 = (int(end, 16) & 0x0000ff) >> 0 if r0 < r1: r = int(((r1-r0)*(float(current_step)/float(max_steps)))+r0) else: r = int(((r0-r1)*(1-(float(current_step)/float(max_steps))))+r1) if g0 < g1: g = int(((g1-g0)*(float(current_step)/float(max_steps)))+g0) else: g = int(((g0-g1)*(1-(float(current_step)/float(max_steps))))+g1) if b0 < b1: b = int(((b1-b0)*(float(current_step)/float(max_steps)))+b0) else: b = int(((b0-b1)*(1-(float(current_step)/float(max_steps))))+b1) return '{0:#x}'.format(((((r << 8) | g) << 8) | b)) 

When I run a loop looking at # 000000, which is black, I return only 0. The second code f0f0f is also missing.

 for i in range(0, 16): print _get_color(current_step=i, start='000000', end='ffffff', max_steps=16) 0 f0f0f 1f1f1f 2f2f2f 3f3f3f 4f4f4f 5f5f5f 6f6f6f 7f7f7f 8f8f8f 9f9f9f afafaf bfbfbf cfcfcf dfdfdf efefef 

Pay attention to the first two hexadecimal codes. Any thoughts on how to format the return value correctly in order to return 000000?

+4
source share
1 answer
 >>> print '{0:06x}'.format(123) 00007b 
+9
source

All Articles