简体   繁体   中英

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?

Use a dictionary to map letters to functions:

def draw_a(): # ...
def draw_b(): # ...

per_letter = {
    'a': draw_a, 'b': draw_b, # ...
}

for char in string:
    if char.isalpha():
        per_letter[char]()

Note that the function object is put in the dictionary, they are not called, not until we look them up in the dictionary with per_letter[char] .

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 ()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM