creating variable names by adding 2 strings?

Remco Gerlich scarblac at pino.selwerd.nl
Mon Jan 22 08:02:20 EST 2001


Lee <lee.reilly at ntlworld.com> wrote in comp.lang.python:
> This is my first post here. I've got a problem, which I can find any
> solutions for using my books or docs on the WWW. I would really
> appreciate it if someone could tell me whether the following is
> possible...
> 
> I'm creating variables in but I am having trouble creating them when
> they're *named* using other variables. Here's an example;
> 
> while (p!=0):
>         p+`p`= string.replace(component[control], ",", "")
>         # e.g. I want 'p1 = string.replace.blah...'
>         p=p-1
>         control=control+1
> 
> ==> SyntaxError: can't assign to operator :(
> 
> I've tried various things but I cannot find a solution. I've got a nasty
> feeling that it's not possible...

It's possible, but rather ugly. When you want to use the variables later,
you don't know what they're called! You'll have to compute their names and
do strange tricks once more.

Lists and dictionaries were invented for this sort of thing.

pdict = {}
while p != 0:
   pdict[p] = string.replace(component[control], ",", "")
   p = p-1
   control = control+1

print pdict

Or make it an empty list ([]), and append the strings to it.
-- 
Remco Gerlich



More information about the Python-list mailing list