aneuryzm
aneuryzm

Reputation: 64834

How to convert colors into strings with the same size?

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.

Upvotes: 0

Views: 595

Answers (4)

unutbu
unutbu

Reputation: 879143

Format can also resolve qualified attributes:

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

Upvotes: 3

Mark Byers
Mark Byers

Reputation: 837996

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)

Upvotes: 4

nmichaels
nmichaels

Reputation: 50943

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.

Upvotes: 4

BudgieInWA
BudgieInWA

Reputation: 2255

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.

Upvotes: 2

Related Questions