Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Removing spaces from list objects [duplicate]

Tags:

python

list

I have a list of objects appended from a mysql database and contain spaces. I wish to remove the spaces such as below, but the code im using doesnt work?

hello = ['999 ',' 666 ']  k = []  for i in hello:     str(i).replace(' ','')     k.append(i)  print k 
like image 687
Harpal Avatar asked Jul 12 '10 23:07

Harpal


People also ask

How do I remove duplicate spaces in Python?

strip() Python String strip() function will remove leading and trailing whitespaces. If you want to remove only leading or trailing spaces, use lstrip() or rstrip() function instead.

Are duplicates allowed in list Python?

Python list can contain duplicate elements.


1 Answers

Strings in Python are immutable (meaning that their data cannot be modified) so the replace method doesn't modify the string - it returns a new string. You could fix your code as follows:

for i in hello:     j = i.replace(' ','')     k.append(j) 

However a better way to achieve your aim is to use a list comprehension. For example the following code removes leading and trailing spaces from every string in the list using strip:

hello = [x.strip(' ') for x in hello] 
like image 70
Mark Byers Avatar answered Sep 30 '22 05:09

Mark Byers