为什么我不能更改字符串中的子字符串?

问题描述 投票:0回答:4

我正在尝试编写一个函数,将字符串中的专用字转换为星号。基本上,我想从字符串中检查一个单词(例如,如果我将“World”作为专用单词,请将“Hello World”更改为“Hello *****”)。我尝试编写以下代码,但代码不会将单词转换为星号。

def censor(text, word):

    a = text.split()

    replace = ""

    for i in word:
        replace += "*"

    for i in a:
        if i == word:
            i = replace

    result =' '.join(a)

    return result

有人能帮我吗?除了行i = replace之外,代码中的所有内容似乎都有效。

谢谢!

python python-3.x
4个回答
2
投票

i = replace将名为i的变量重新绑定到replace中的字符串。它不会像您期望的那样更新列表。您可以通过使用索引将replace分配给列表中的项来修复代码:

for idx, s in enumerate(a):
    if s == word:
        a[i] = replace

现在列表a中的项目将会更新。


2
投票

如果您只是想更改字符串中的子字符串,可以使用以下内容:

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

这将替换所有word的实例与*足够的len(word)s。


我的回答只是意识到问题是,如果你想要审查“世界”而不是“世界破坏者”,你会遇到问题,因为你最终会得到“*****破坏者”。

在这种情况下,我会说做类似的事情:

censor(text, word):
    a = [w if w!=word else '*'*len(w) for w in text.split()]
    return ' '.join(a)

在第二行,我们让每个w(来自text.split()的一个词)保留,除非它是word,在这种情况下,我们用*替换它足以填补。然后我们加入空格并返回


1
投票

这可能有所帮助

def censor(text, word):
    a = text.split()
    for i, v in enumerate(a):
        if v == word:
            a[i] = "*"*len(v)
    return  ' '.join(a)

print censor("Hello World", "World")

输出:

Hello *****

0
投票

您始终可以使用find()方法。

def replaceWord(word, sentence):
    # find the starting position
    posStart = sentence.find(word)

    # find the ending position
    posEnd = posStart + sentence[posStart:].find(" ") - 1

    # Get the word
    new_word = sentence[posStart:posEnd+1]

    # Turn word into a list
    list_word = list(new_word)

    # Find length of word
    word_length = len(sentence[posStart:posEnd + 1])

    # replace the word with "*"
    star = ""
    for i in list_word:
        star = star + i.replace(i, "*")

    # Add back in sentence
    new_sentence = sentence[0:posStart - 1] + " " + star + " " + sentence[posEnd +2:]
    return new_sentence

print(replaceWord("fox", "The fox is there"))
© www.soinside.com 2019 - 2024. All rights reserved.