用星号替换文本的脚本无效

2024-06-16 13:58:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图让这个函数返回“**************”(显然不是成品,只是想一步一步地弄清楚它是如何工作的),但是这段代码只返回文本而不替换任何内容。在我看来,它应该检查字符串“Text”中的每个值,然后对于每个值,用星号替换该值I。我在这里哪里做错了?在

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

Tags: 函数字符串代码textin文本内容for
1条回答
网友
1楼 · 发布于 2024-06-16 13:58:30

您想替换整个单词,然后将其替换为*,因为您要替换的单词有多个字母:

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

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

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

相关问题 更多 >