Assigning and Calling built-in functions from a dictionary (Python)

everyone. I am trying to solve a coding challenge as follows:

  1. get a string from the user. Afterward, ask the user "What would you like to do to the string?", allow the user to choose the next functionalities: "upper" - makes all the string upper case "lower" - makes all the string lower case " "spaces2newline" - reaplce all spaces in new lines ... print the result *Use a dictionary to "wrap" that menu

So, what I am getting from this is that I need to make a dictionary from which I can call commands and assign them to the string.

Obviously, this doesn't work:

commands = {"1" : .upper(), "2" : .lower(), "3" : .replace(" ",\n)}

user_string = input("Enter a string: ")
options = input("How would you like to alter your string? (Choose one of the following:)\n
\t1. Make all characters capital\n
\t2. Make all characters lowercase")
#other options as input 3, 4, etc...

But perhaps someone can recommend a way to make the idea work?

My main questions are:

  1. Can you somehow assign built-in functions to a variable, list, or dictionary?
  2. How would you call a function like these from a dictionary and add them as a command to the end of a string?

Thanks for any assisstance!


Use operator.methodcaller.

from operator import methodcaller


commands = {"1": methodcaller('upper'),
            "2": methodcaller('lower'),
            "3": methodcaller('replace', " ", "\n")}

user_string = input("Enter a string: ")
option = input("How would you like to alter your string? (Choose one of the following:)\
\t1. Make all characters capital\
\t2. Make all characters lowercase")

result = commands[option](user_string)

The documentation shows a pure Python implementation, but using methodcaller is slightly more efficient.


Well, chepner's answer is definitely much better, but one way you could have solved this is by directly accessing the String class's methods like so:

commands = {"1" : str.upper, "2" : str.lower, "3" : lambda string: str.replace(string, " ", "\n")}  # use a lambda here to pass extra parameters

user_string = input("Enter a string: ")
option = input("How would you like to alter your string? (Choose one of the following:)\
\t1. Make all characters capital\
\t2. Make all characters lowercase")

new_string = commands[option](user_string)

By doing this, you're saving the actual methods themselves to the dictionary (by excluding the parenthesis), and thus can call them from elsewhere.