'Why isn't the replace method in Python working when iterating through a list of strings?

I have a list of strings that I am iterating through. With each element/iteration I am trying to take the string and remove all non-alphabetic characters(numbers, punctuations, spaces, and more). However, when using a nested for-loop to access the individual characters and using replace function it is not working.

import string

new_war = ['I am the new king of Mississippi', 'next one you know', 'i got a family to feed']
print(new_war)

alphabet = string.ascii_uppercase + string.ascii_lowercase

def remove_char(lst):
    for word in lst: #takes the individual string/element from the list
        for chars in word: #goes through each individual character in the word element
            if chars not in alphabet: #check to see if that character is in the alphabet(upper and lower)
                word = word.replace(chars, "") #should take the given string, remove all occurrences of that char in the string via "", 

remove_char(new_war)


Solution 1:[1]

If you want to modify the original list items, then you have to operate on them directly.

def remove_char(lst):
    for i in range(len(lst)):
        for chars in lst[i]:
            if chars not in alphabet:
                lst[i] = lst[i].replace(chars, "")

Note how this code refers to lst[i], not a local variable.

Solution 2:[2]

As already pointed out when you use

for word in lst:

you get the value "word" (edit: a reference to the same immutable string), which is a string. Basically a copy (edit : new reference) of it, for that one iteration of the loop. That means whatever you do to "word" then, it applies to (edit : a new immutable string, to which you re-reference your variable, which is when a new allocation must be made) that copy, not what is inside your list.

To make things more practical, I suggest you use the enumerate() function of python.

As such :

import string

new_war = ['I am the new king of Mississippi', 'next one you know', 'i got a family to feed']

alphabet = string.ascii_uppercase + string.ascii_lowercase


def remove_char(lst):
    for key, word in enumerate(lst):  # takes the individual string/element from the list
        for chars in word:  # goes through each individual character in the word element
            if chars not in alphabet:  # check to see if that character is in the alphabet(upper and lower)
                lst[key] = word.replace(chars,
                                        "")  # should take the given string, remove all occurrences of that char in the string via "",


remove_char(new_war)

print(new_war)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2