Python Forum

Full Version: Assignment Help
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello, i've been asked in my assignment to create a censor function that replaces words in a text string with astricks of the same lenght if the word is in a banned list. I have wriiten a fucntion i thought would work however i cant seem to get it correct, it keeps failing the validations. Id appreciate any help at all! i just want to learn what im doing wrong with this so i can fix it. Thanks so much in advance! ill insert the full question and my answer that has failed validatons below.

Write a function censor which takes as input a string text and a list of strings banned. Your function should return a string which is obtained from text by replacing each occurrence of any string from banned in text by the string consisting of the same numbers of asterisks (*).

For example:

censor('This is appaling and outrageous.', ['appaling', 'outrageous']) should return 'This is ******** and **********.'

censor('I strongly dislike this problem.', ['dislike', 'hate']) should return 'I strongly ******* this problem.'

Note. You may assume that no string in banned occurs as a substring of any other string in banned.



def censor(text, banned):
    for i in banned:
        if i in text:
            text = text.replace(i,'*'*len(i), len(text.split()))
        return text
when i run the function with an input, the output only censors 1 word from the list banned even if there are more than one.
[in] censor('hello i am h', ['i', 'am'])
[out]'hello * am h'
Remove the 3rd parameter in your call to replace()
(Nov-08-2020, 11:00 PM)jefsummers Wrote: [ -> ]Remove the 3rd parameter in your call to replace()
Hello,
Thank you for your help! I tried this before and unfortunately it returned the same output (it replaces the first banned word but does not replace the secnond) and didnt pass the validation.
(Nov-08-2020, 10:44 PM)HNiChuimin Wrote: [ -> ]create a censor function that replaces words in a text string with astricks of the same lenght if the word is in a banned list.
/.../

[b]Write a function censor which takes as input a string text and a list of strings banned. Your function should return a string which is obtained from text by replacing each occurrence of any string from banned in text by the string consisting of the same numbers of asterisks (*).

One should always read assignments carefully. I am afraid that your interpretation of objective is not correct. This is not about replacing 'words'. It is about replacing strings. Difference? Text: 'haven', banned string: 'have'. In case of replacing words no changes needed, but as assignment description is given this should actually return ****n