Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

replace function in python not working in my code

def rmv_spc(lst,a):
        a = str(a)
        for i in lst:
            i = str(i)
            i.replace(a,"")
        return lst
    print(rmv_spc([343, 893, 1948, 3433333, 2346],3))

Tried multiple ways but output is the same list always.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Using i.replace(a, "") only returns the replaced string. You need to assign the result back into your list. To do this, you need to edit lst with an index i:

def rmv_spc(lst, a):
    a = str(a)
    for i in range(len(lst)):
        x = str(lst[i])
        lst[i] = x.replace(a, "")
    return lst

A better way would be to use a list comprehension:

def rmv_spc(lst, a):
    a = str(a)
    return [str(x).replace(a, "") for x in lst]

This is how replace works:

# Assign x
>>> x = 'abc'
>>> x
'abc'
# Replace 'a' with nothing
>>> x.replace('a','')
'bc'
# That is the result that we wanted, but x is still the same
>>> x
'abc'
# So we need to say that x = that result
>>> x = x.replace('a','')
>>> x
'bc'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading