Dynamic variable names
Steve Holden
steve at holdenweb.com
Sun Feb 7 08:31:24 EST 2010
R (Chandra) Chandrasekhar wrote:
> Dear Folks,
>
> I have read that one should use a dictionary in python to accommodate
> dynamic variable names. Yet, I am puzzled how to achieve that in my
> case. Here is what I want to do:
>
> 1. The user inputs a number of six-digit hex numbers as a
> comma-separated list. These numbers represent colours, but the number of
> colours is not known beforehand.
>
> 2. Using these colours in pairs, I am generating image files whose names
> must be unique. I could use the respective hex numbers for this, but
> would like to explore generating filenames like
>
> colour_1-colour_2.jpg
>
> Because I do not know how many colours there would be in advance, I need
> to generate the colour_n names on the fly.
>
> So, my two questions are:
>
> 1. How do I do this properly in python?
>
> 2. If there is a better scheme than what I have outlined, can someone
> please point me to a Web link?
>
Here's one way, though not necessarily the best:
>>> import itertools
>>> ctr = itertools.count(1)
>>> for i in range(5):
... print "colour_%03d-colour%03d.jpg" % (ctr.next(), ctr.next())
...
colour_001-colour002.jpg
colour_003-colour004.jpg
colour_005-colour006.jpg
colour_007-colour008.jpg
colour_009-colour010.jpg
>>>
I zero-filled the names so they sort in numerical order. If this isn't a
requirement then simply change the format string to
"colour_%d-colour%d.jpg"
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010 http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS: http://holdenweb.eventbrite.com/
More information about the Python-list
mailing list