0

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

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.