简体   繁体   中英

Why does one function work while the other doesn't?

Going through codeacademy for python, one task was to write a function that would take a string and have a certain word censored out with asterisks, and then return the string. I tried it one way and it didn't work but I then tried it another way and it did. I just was curious as to why.

The one that didn't work:

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)

The one that did work:

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)

The following statement make i references the value that the replace_string reference, and it does not affect list item.

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]

while, lst[<number>] = replace_string changes the list item inplace.

>>> 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)

This didn't work because all you did was assign the name, i , to another string. Instead, you might build up a new list, or replace the string in the original list as you did in your second example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM