imfromsweden
imfromsweden

Reputation: 169

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:
    element = element.replace('\xa0',' ')

But it didn't work. Also, when I print the elements, it prints:

print(lista[0])
Jeux Olympiques De Rio 2016

Does anyone have an idea on how to solve this?

Upvotes: 3

Views: 6075

Answers (3)

Sergey Luchko
Sergey Luchko

Reputation: 3356

the easiest way:

lista = [el.replace('\xa0',' ') for el in lista]

Upvotes: 4

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160607

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:

for elem in lista

and replace all strings that contain \xa0 i.e:

elem if '\xa0' not in elem else elem.replace('\xa0', '')

Upvotes: 3

James
James

Reputation: 2721

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.

Upvotes: 3

Related Questions