Home > Software engineering >  Unable to replace characters in a list
Unable to replace characters in a list

Time:04-23

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))

The output is the always the same list.

CodePudding user response:

This would work,

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

  return lst 

print(rmv_spc([343, 893, 1948, 3433333, 2346],3))

Output -

['4', '89', '1948', '4', '246']

Your code was successfully replacing the characters from each item in the list, but it wasn't replacing the old item with the new one.

CodePudding user response:

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'
  • Related