[python] Python: Removing spaces from list objects

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

This question is related to python list

The answer is


result = map(str.strip, hello)

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)


String methods return the modified string.

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

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]

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

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