Censor


#1

Hi, I'm working on the Censor program right now. I know that there's an easier way to replace the word with asterisks but I tested this out earlier and it works just fine so I know that's not the issue.

I'm currently getting an error that says that the program isn't replacing "hey hey hey" with "*** *** ***" so it would be awesome if y'all could take a look at the code below. I probably made this way too complicated but I hope that in the end it can work with the methods I have already. Thanks so much!


def censor(text, word):
    #count word in text and locations
    single_words = text.split()         #splits text by spaces
    
    #replace word with asterisk per character -> turns into a string of asterisks
    word = list(word)
    for character in word:
        character_index = word.index(character)
        word[character_index] = "*"
    asterisks = "".join(word)

    #censoring yayy
    for index in single_words:
        if index == word:
            single_words[single_words.index(index)] = asterisks
    return " ".join(single_words)


#2

here is your code with some print statements:

def censor(text, word):
    #count word in text and locations
    single_words = text.split()         #splits text by spaces
    
    #replace word with asterisk per character -> turns into a string of asterisks
    word = list(word)
    for character in word:
        character_index = word.index(character)
        word[character_index] = "*"
    asterisks = "".join(word)

    #censoring yayy
    for index in single_words:
        print index, word
        if index == word:
            single_words[single_words.index(index)] = asterisks
    return " ".join(single_words)
print censor("hey hey hey", "hey")

this allows you to see where you go wrong:

if index == word:

as you can see thanks to print, this condition can never be true. It seems you overwritten word.


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.