Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I've written this code for removing characters from a string. I used the filter function but it returns the same list without modification.

a = "Hello !!!!,  . / "

a1 = list(a)

def it(at):

    k = at.copy()

    charlist = [",", ".", "/", " ", ":", ";", "\'", "\"", "!"]

    for x in charlist:

        filter(lambda t: t != x, k)

    print(k)

it(a1)

1 Answer

0 votes
by (36.8k points)
edited by

Filter returns the filtered iterable; it doesn't modify it in place.

>>> def it(at):

...     charlist = [",", ".", "/", " ", ":", ";", "\'", "\"", "!"]

...     print(list(filter(lambda t: t not in charlist, at)))

...

>>> it(a1)

['H', 'e', 'l', 'l', 'o']

An implementation closer to your original code would be to filter in a loop the way you were doing, but to reassign k each time:

>>> def it(at):

...     k = at.copy()

...     charlist = [",", ".", "/", " ", ":", ";", "\'", "\"", "!"]

...     for x in charlist:

...         k = list(filter(lambda t: t != x, k))

...     print(k)

...

>>> it(a1)

['H', 'e', 'l', 'l', 'o']

If you want to know more about the Data Science then do check out the following Data Science which will help you in understanding Data Science from scratch 

Browse Categories

...