Home > Back-end >  get user input of variable name python
get user input of variable name python

Time:08-18

I'm trying to figure out how to get from user string which direct me which variable should I use. I have to following code:

general_string = "this is just general string"
user_specfic_string = "this is user string"

def relevant_string_to_print(user_string):
    relevant_string = ""
    if user_string in vars():
       #here I do logic which I'm not sure about
    else:
       relevant_string = general_string
    
    print(relevant_string)


relevant_string_to_print("user_specfic_string")
relevant_string_to_print("arbitrary_string")

requested output:

this is user string
this is just general string

CodePudding user response:

It's not a good practice to use vars() here. Create a dictionary instead:

general_string = "this is just general string"
user_specfic_string = "this is user string"

mapping = {
    "user_specfic_string": user_specfic_string,
}


def relevant_string_to_print(user_string):
    return mapping.get(user_string, general_string)


print(relevant_string_to_print("user_specfic_string"))
print(relevant_string_to_print("arbitrary_string"))

Output:

this is user string
this is just general string

CodePudding user response:

Its easier to ask forgiveness than permission - per the python docs -

You can do something like this -

default_string = "default string"
try:
    print(user_string)
except NameError:
    print(default_string)
  • Related