jeudi 16 septembre 2021

What is a pythonic way of checking for words in a string and setting a variable accordingly?

I might be overthinking this, but I'm currently facing this code:

result = None
if my_string.lower().contains('word_a'):
    result = do_action_A()
elif my_string.lower().contains('word_b'):
    result = do_action_B()
elif my_string.lower().contains('word_c'):
    result = do_action_C()
etc.

I'm trying to think of a nicer / more pythonic /readable way of doing this, but my brain seems empty for solutions. It is somehow related to this question I asked years ago, but it's not exactly the same, since it's not simply a string comparison which can be substituted with a dictionary lookup.

Does anybody know a more Pythonic way of doing this?

To be clear; I'm not specifically looking for more performance, but rather for elegant/readable code.

Aucun commentaire:

Enregistrer un commentaire