Ramkrishna Melgiri
Ramkrishna Melgiri

Reputation: 11

python censor function by codeacademy

def censor(text, word):
    final_text = ''
    new_text = ''
    items = text.split()
    for i in items:
        if i == word:
            new_text = "*" * len(word)
            final_text.join(new_text)
        else:
            new_text = items
            final_text.join(new_text)
    return final_text

print censor("this hack is wack hack", "hack")

the above function is intended to censor the word "hack" with asterisks present in the text. Can I know where is the flaw in the above code. Thank you in advance.

Upvotes: 0

Views: 199

Answers (1)

admix
admix

Reputation: 1782

This should be it.

def censor(text, word):
    final_text = ''
    new_text = ''
    items = text.split()
    for index, w in enumerate(items):  #'index' is an index of an array
        if w == word:
            new_text = "*" * len(word)
            items[index] = new_text # substituting the '*'
    final_text = ' '.join(items)    # the correct way how join works
    return final_text

print censor("this hack is wack hack", "hack")

The other way:

text = 'this hack is wack hack'
word = 'hack'
print text.replace(word, '*' * len(word)) 

The way join() works in python is you execute it on a join sign (e.g. ' ', '-', ',' etc), and you provide the list inside the join(list_in_here)

Simple example:

>>>'-'.join(['1','human','is','a','one'])
'1-human-is-a-one'

Upvotes: 1

Related Questions