Removing \xa0 From String In A List
I have a list with a bunch of words: lista = ['Jeux Olympiques De Rio\xa02016', 'Sahara Ray', 'Michael Phelps', 'Amber Alert'] I tried to replace the '\xa0': for element in listor
Solution 1:
the easiest way:
lista = [el.replace('\xa0',' ') for el in lista]
Solution 2:
for index, element in enumerate(listor):
listor[index] = element.replace('\xa0',' ')
Now you're replacing the string within the list rather than trying to change the string itself. Previously, you were assigning a new string to the same variable name, which doesn't change the previous string but just changes the string that the "element" variable is pointing to. With this, you'll be actually overwriting the list element with a new string.
Solution 3:
Just use a list comprehension to replace the ending if a string contains '\xa0'
:
res = [elem if '\xa0' not in elem else elem.replace('\xa0', '') for elem in lista]
Your current approach merely re-assigns a name (element
) over and over without actually modifying the list lista
. The list comprehension will create a new list with elements from the original list, i.e:
forelemin lista
and replace all strings that contain \xa0
i.e:
elem if'\xa0' not in elem else elem.replace('\xa0', '')
Post a Comment for "Removing \xa0 From String In A List"