Trying To Understand What's Happening Here

Hi all.

I’ve been recently doing the intermediate DA path on python and was understanding it completely until I got to this part. So, we have a list of strings and a list of bad characters:

list_of_strings = ["good!", "morn?ing", "good?!", "morniZZZZng"]
bad_chars = ["!", "?", "Z"]

Then a function is created to replace each of the bad strings with an empty string:

def strip_characters(string):
    for char in bad_chars:
        string = string.replace(char,"")
    return string

What I don’t understand is why when I put list_of_strings into that function and print it doesn’t return a clean list of [“good”, “morning”, “good”, “morning”].

Can anyone help clarify this for me?

*sidenote: the solution offered on the task is as follows: *

cleaned_strings = []
for s in list_of_strings:
    s = strip_characters(s)


I want to try and understand the logic behind this cause I can’t quite grasp it from the explanation.

I am assuming that when you try to do the above it throws an error. And it should be producing an error.

That’s because when you run the following -


Your code tries to run the following - string.replace(char,"")

The issue is that string in the above, is a list. And a Python list does not have a method/function called replace().

replace() is a method/function for String data type in Python. So, you can only use it on an actual string and not for a list. Python does not know that you want to apply replace() to the elements inside of that list_of_strings. You need to write your code to make sure of that.

That’s why in the solution you have the following -

for s in list_of_strings:
    s = strip_characters(s)

You will iterate through the list. s would be a string that is stored in list_of_strings, like "good!". And then strip_characters() function will replace any bad_chars present in s and replace it as needed.

1 Like


Hey, as @the_doctor said you can not use replace method on a list.

You need to iterate through each element and apply the replace function.

If you want to achieve this then you have to modify function as follow:

def strip_characters(list_of_strings):
     cleaned_strings = []
     for string in list_of_strings:
         for char in bad_chars:
             string = string.replace(char,"")
    return cleaned_strings
1 Like

Wow, thank you so much for clarifying. This helped immensely.

1 Like