Reputation: 5361
I have a question that may be straight forward, or may be impossible to answer, I'm not sure. I'm wondering how I can define a color in python.
For example, I would like to simply do this:
myColor = #920310
However, using the '#' sign in python automatically comments anything following. Is there a way around this? Thank you and sorry if this question is very simple
Upvotes: 7
Views: 48470
Reputation: 86844
Depending on how you are planning to use the values, you have many options:
colorString = "#920310"
colorList = [0x93, 0x03, 0x10]
colorTuple = (0x93, 0x03, 0x10)
colorDict = {
"R" : 0x93,
"G" : 0x03,
"B" : 0x10,
}
Or, if you're planning to have several operations to deal with your color, say convert to different formats, you can define a Color class:
class Color(object):
def __init__(self, r, g, b):
self._color = (r,g,b)
def get_tuple(self):
return self._color
def get_str(self):
return "#%02X%02X%02X" % self._color
def __str__(self):
return self.get_str()
def get_YUV(self):
# ...
Example usage:
>>> a = Color(0x93, 0x03, 0xAA) # set using hex
>>> print a
#9303AA
>>> b = Color(12, 123, 3) # set using int
>>> print b
#0C7B03
Upvotes: 3
Reputation: 9163
myColor = int('920310', 16) #as an integer (assuming an RGB color in hex)
myColor = '#920310' #as a string
from collections import namedtuple
Color = namedtuple("Color", "R G B")
myColor = Color(0x92, 0x03, 0x10)
#as a namedtuple
There are lots of things you could be looking for, and equally many ways to use it. Ultimately, it depends on how you want to use this color.
Upvotes: 3
Reputation: 176740
If you want it as a string, do
myColor = '#920310'
If you actually want it to be a Color
object, you can do something like
myColor = Color('#920310')
and interpret it in Color
's constructor.
If the question is can you make #
not be interpreted as a comment, then the answer is no. If #
wasn't a comment, it wouldn't be Python any more.
You could define your own, Python-like language where a #
after an =
wouldn't mean a comment (since that's not valid Python anyway) and it wouldn't break any code, but you wouldn't be able to use the #
syntax elsewhere without breaking code.
Upvotes: 12
Reputation: 11038
mycolor = '#<colorcodehere>'
mycolor will be seen as a string, so everything inside the apices will be read (# too)
Upvotes: 2