Python: Removing spaces from list objects

PythonList

Python Problem Overview


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

Python Solutions


Solution 1 - Python

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]

Solution 2 - Python

List comprehension [num.strip() for num in hello] is the fastest.

>>> import timeit
>>> hello = ['999 ',' 666 ']

>>> t1 = lambda: map(str.strip, hello)
>>> timeit.timeit(t1)
1.825870468015296

>>> t2 = lambda: list(map(str.strip, hello))
>>> timeit.timeit(t2)
2.2825958750515269

>>> t3 = lambda: [num.strip() for num in hello]
>>> timeit.timeit(t3)
1.4320335103944899

>>> t4 = lambda: [num.replace(' ', '') for num in hello]
>>> timeit.timeit(t4)
1.7670568718943969

Solution 3 - Python

result = map(str.strip, hello)

Solution 4 - Python

String methods return the modified string.

k = [x.replace(' ', '') for x in hello]

Solution 5 - Python

Presuming that you don't want to remove internal spaces:

def normalize_space(s):
    """Return s stripped of leading/trailing whitespace
    and with internal runs of whitespace replaced by a single SPACE"""
    # This should be a str method :-(
    return ' '.join(s.split())

replacement = [normalize_space(i) for i in hello]

Solution 6 - Python

for element in range(0,len(hello)):
      d[element] = hello[element].strip()

Solution 7 - Python

replace() does not operate in-place, you need to assign its result to something. Also, for a more concise syntax, you could supplant your for loop with a one-liner: hello_no_spaces = map(lambda x: x.replace(' ', ''), hello)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHarpalView Question on Stackoverflow
Solution 1 - PythonMark ByersView Answer on Stackoverflow
Solution 2 - PythonrizaView Answer on Stackoverflow
Solution 3 - PythonyedpodtrzitkoView Answer on Stackoverflow
Solution 4 - PythonIgnacio Vazquez-AbramsView Answer on Stackoverflow
Solution 5 - PythonJohn MachinView Answer on Stackoverflow
Solution 6 - PythonHassan AnwerView Answer on Stackoverflow
Solution 7 - PythonallonymView Answer on Stackoverflow