[Tutor] Concatenating Strings into Variable Names?

don arnold darnold02 at sprynet.com
Mon Feb 2 13:37:11 EST 2004


----- Original Message -----
From: "steve" <xthereal at bigfoot.com>
To: <tutor at python.org>
Sent: Monday, February 02, 2004 12:12 PM
Subject: [Tutor] Concatenating Strings into Variable Names?


> Hello,
> I'm a day 1 complete newcomer to python and programming in general,
> so I apologize in advance for any stupid questions or code butchering
> that may follow...
> I'm trying to write my first program besides good old hello world. Is
> there a way to concatenate strings into a variable name? Here's a
> brief example of what i'm trying to do:
>
> choiceA_option1= 2.0
> choiceA_option2= 3.0
> choiceB_option1= 4.0
> choiceB_option2= 5.0
>
> choice=raw_input("Do you want choice A or B?")
> option=raw_input("Do you want option 1 or 2?")
>
> the_answer="choice" + choice + "_option" + option
>
> print the_answer
>
>
> When i run this, and type in A and 2, it sets the_answer as choiceA_
> option2 and prints "choiceA_option2" as another string instead of the
> value 3.0. Is there a way to set the resulting concatenation of the_
> answer as the variable name that i set previously, and not a literal
> string?
>

This seems to be a very common question. Instead of using a 'regular'
variable, you create a dictionary to hold your data. Then you use a string
representing the variable's name as the key to that dictionary:

myvars = {}
myvars['choiceA_option1'] = 2.0
myvars['choiceA_option2'] = 3.0
myvars['choiceB_option1'] = 4.0
myvars['choiceB_option2'] = 5.0

choice=raw_input("Do you want choice A or B?")
option=raw_input("Do you want option 1 or 2?")

the_answer = "choice" + choice + "_option" + option

if the_answer in myvars:
    print 'answer:', myvars[the_answer]
else:
    print 'invalid choice/option combination'


> Hope this question makes some sense, and sorry for any misuse of terms.
>  Gotta start somewhere lol
>
> Thanks for any help!

HTH,
Don




More information about the Tutor mailing list