electronicaneer
electronicaneer

Reputation: 65

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)

Upvotes: 1

Views: 70

Answers (2)

Aaron Hall
Aaron Hall

Reputation: 394825

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.

Upvotes: 1

falsetru
falsetru

Reputation: 368924

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]

Upvotes: 1

Related Questions