tags:

views:

47

answers:

4

I'm converting color values to string values, however when I get 0, the string is too short and I have to manually add "00" after it.

Whats the most elegant way to solve this issue in Python ?

print "#" + str(self.R) + str(self.G) + str(self.B)

if self.R is 0 then I get a too short string.

+1  A: 
print "#" + str(self.R).rjust(2,"0") + str(self.G).rjust(2,"0") +
    str(self.B).rjust(2,"0")

will work fine. It will turn 0 into 00 and 1 into 01 etc.

BudgieInWA
+4  A: 

Use formatting strings:

"#%02X%02X%02X" % (self.r, self.g, self.b)

will give you what you probably want. If you actually want your values to be in decimal like in your example, use "%03d" instead.

Nathon
+3  A: 

Assuming you are using Python 2.6 or newer you can use str.format:

print "#{0:02}{1:02}{2:02}".format(self.R, self.G, self.B)

If you want hexadecimal (probably you do) then add an X:

print "#{0:02X}{1:02X}{2:02X}".format(self.R, self.G, self.B)
Mark Byers
@Mark Byers I get the following error: print "#{0:02}{1:02}{2:02}".format(self.R, self.G, self.B)ValueError: '=' alignment not allowed in string format specifier
Patrick
+2  A: 

Format can also resolve qualified attributes:

print('#{s.R:02x}{s.G:02x}{s.B:02x}'.format(s=self))
unutbu