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.
Wha开发者_如何学编程ts 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.
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.
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)
Format can also resolve qualified attributes:
print('#{s.R:02x}{s.G:02x}{s.B:02x}'.format(s=self))
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.
精彩评论