0

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="$")

2
  • 1
    If you want to pass a list as an argument you can do that just like with any other variable and treat is as a normal list in the code. Commented Feb 9, 2022 at 10:42
  • I tried and it does not work. Commented Feb 9, 2022 at 10:50

1 Answer 1

2

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'
Sign up to request clarification or add additional context in comments.

6 Comments

NameError: name 'cenzura' is not defined
I'm just using the same cenzura function that you defined in your question :-)
Ok, now I got it. So we have two functions. One is mine and second is yours. So we cannot do the task within one function?
@butterflyknife Instead of overloading you can also just check for type of variable with isinstance()
Ok, let stay with current way.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.