为什么一个函数起作用而另一个不起作用?

2024-04-23 22:17:02 发布

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

通过codeacademy for python,一项任务是编写一个函数,该函数将获取一个字符串并用星号删除某个单词,然后返回该字符串。我试了一种方法,但没有成功,但我试了另一种方法,它成功了。我只是好奇为什么。你知道吗

不起作用的那个:

def censor(text, word):
    split_string = text.split()
    replace_string = "*" * len(word)
    for i in split_string:
        if i == word:
            i = replace_string 
    return " ".join(split_string)

其中一个确实有效:

def censor(text, word):
    split_string = text.split()
    replace_string = "*" * len(word)
    for i in range(0, len(split_string)):
        if split_string[i] == word:
            split_string[i] = replace_string
    return " ".join(split_string)

Tags: 方法函数字符串textinforstringlen
2条回答

下面的语句使i引用replace_string引用的值,并且它不影响列表项。你知道吗

i = replace_string

>>> lst = [1, 2, 3]
>>> i = lst[0]
>>> i = 9
>>> i   # affects `i`
9
>>> lst # but does not affect the list.
[1, 2, 3]

lst[<number>] = replace_string则将列表项更改到位。你知道吗

>>> lst[0] = 9
>>> lst
[9, 2, 3]
def censor(text, word):
    split_string = text.split()
    replace_string = "*" * len(word)
    for i in split_string:
        if i == word:
            i = replace_string # This doesn't work*
    return " ".join(split_string)

这不起作用,因为您所做的只是将名称i分配给另一个字符串。相反,您可以建立一个新的列表,或者像在第二个示例中那样替换原始列表中的字符串。你知道吗

相关问题 更多 >