2017-04-23 54 views
1

我試圖讓這個函數返回「****** * * *********」(顯然不是成品,只是試圖找出它是如何工作的),但這段代碼只是返回文本而不替換任何東西。我看到它的方式,它應該檢查字符串「文本」中的每個值,然後爲每個值,用星號替換該值i。我在哪裏錯了?用星號代替文本的腳本不工作

def censor(text, word): 
    for i in text: 
     text.replace(i, '*') 
    return text 
print censor("Hello, you are beautiful", "beautiful") 

回答

1

要替換整個單詞,然後你想,因爲有你要替換詞的字母與儘可能多的*替換此:

def censor(text, word): 
    return text.replace(word, '*' * len(word)) 

print censor("Hello, you are beautiful", "beautiful") 

# returns: Hello, you are ********* 
+0

知道了,沒考慮向替代品添加修飾符。 TYVM – Cdhippen