Search code examples
pythonstringfilenamesraw-input

How do I have user's response to raw_input( ) access a string of the same name?


I am attempting to have two pieces of user input become parts of a filename that my Python script will then access.

For example, I want to use the pieces of user input to construct: date_time_place.txt. I know I can do that by concatenating strings.

I ask the user for raw_input() for date and time, but I have named the date and time options they can use:

date1 = yesterday
date2 = today
date3 = tomorrow

time1 = morning
time2 = afternoon
time3 = evening

I specify that the user must enter his or her response as date# or time#.

What I want is to be able to use his or her response to obtain what date# or time# already is assigned to be. How does one go about such a thing?


Solution

  • Although you can, you should not attempt this. Put your variables in a dictionary instead;

    dates = {
        'date1': yesterday,
        'date2': today,
        'date3': tomorrow,
    }
    
    times = {
        'time1': morning,
        'time2': afternoon,
        'time3': evening,
    }
    

    Now access is as simple as dates[userstring] or times[userstring].

    You could access local variables with the locals() function, globals with globals() (both return a dictionary), but you then cannot constrain the names they have access to.