[SOLVED] Python: function with list in arguments

Issue

I created a function which replace word by special characters in string.
It works well once I need to replace only one word.
Now I need to have possibility to extend list of words from one to more (2, 3 4…).

Working code for one argument – word you can find below.
What I need now is to have possibility to insert more than one word so it could be replaced in code by special signs.

def cenzura(text, word, sign="#"):
   if word in text:
       return text.replace(word, len(word)*sign)
   else:
       return text

cenzura("The day when I left", "day", sign="$")

Solution

If you are happy masking all words in the list with the same symbol:

def cenzura_list(text, word_list, sign="#"):
    for word in word_list:
        text = cenzura(text, word, sign)
    return text

cenzura_list("The day when I left", ["day", "I"], sign="$") # 'The $$$ when $ left'

To add: if you do need to mask different words with different symbols, you can use a dict.

def cenzura_dict(text, mapping_dict):
    for word in mapping_dict.keys():
        text = cenzura(text, word, mapping_dict[word])
    return text

cenzura_dict("The day when I left", {"day":"%", "I":"$"}) # 'The %%% when $ left'

Answered By – butterflyknife

Answer Checked By – Cary Denson (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *