Search code examples
pythonstringfunctiontkinterpython-3.5

How to, in Python, execute function corresponding to each letter in a string?


Say, for example, in tkinter, someone created a function corresponding to each of the 26 letters of the English alphabet. Then, he/she wants to be able to take a string provided by the user, make all the uppercase letters lowercase, and then execute the function(s) corresponding to each letter of the string. Here is a pseudocode example of what I am talking about:

# The functions should draw, on a tkinter canvas, the letter each function corresponds to (a pseudocode example shown below):
a -> draw_a
b -> draw_b
c -> draw_c
d -> draw_d
# So on, so forth...

str = input('Enter a string please: ').lower()
for i in str:
    if i is # a letter:
        # execute function corresponding to current letter in string
    else:
        pass # If current character is not a letter

Is it possible to do this in Python? If so, how would I implement this ability?


Solution

  • I assume you want the following:

    If you have an 'a', call function draw_a

    In that case you can use:

    letter='a'
    locals()["draw_"+letter]()
    

    or, in your case:

    for i in str:
    if i is # a letter:
        locals()["draw_"+i]()
    else:
        pass # If current character is not a letter
    

    locals() is a dict containing all defined functions and some other stuff.

    Calling locals()["draw_a"] returns the funtion draw_a as variable, which you then execute using ()