78

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
Harpal
  • 799
  • 1
  • 8
  • 7

7 Answers7

160

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]
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • 21
    +1 for strip. -1 for replace(' ','') – S.Lott Jul 12 '10 at 23:07
  • 1
    OP wants to remove *all* spaces, not just trailers, so why -1 for `replace(' ','')`? None of the 'strip' methods, much less the other [built-in str methods](http://docs.python.org/library/stdtypes.html#string-methods), do the job (ignoring Rube Goldbergs like `''.join(s.split())`). – Mike DeSimone Jul 12 '10 at 23:33
  • Ah, so it isn't a text field that used spaces to separate thousands, millions, etc. that is defined as text because it might contain the occasional keyword? OK, I missed that. – Mike DeSimone Jul 12 '10 at 23:46
  • 2
    The second element in the OP's list has 5 chars. Leading and trailing space – John La Rooy Jul 12 '10 at 23:59
  • 1
    Since the example shows no internal spaces, I'm suspicious about removing internal spaces. – S.Lott Jul 13 '10 at 02:39
21

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
riza
  • 16,274
  • 7
  • 29
  • 29
13
result = map(str.strip, hello)
yedpodtrzitko
  • 9,035
  • 2
  • 40
  • 42
  • 5
    There is no need to use the `lambda`; instead you could use: `result = map(str.strip(), hello)`. However, As mentioned by @riza, in Python 3 map returns an iterator instead of a list. So best practice would be `result = list(map(str.strip(), hello))`. – amicitas Dec 15 '12 at 06:16
  • 5
    Note that (in Python 3 at least) you must say `map(str.strip, mylist)` not `map(str.strip(), mylist)`. – William Mar 08 '13 at 16:25
7

String methods return the modified string.

k = [x.replace(' ', '') for x in hello]
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
4

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]
John Machin
  • 81,303
  • 11
  • 141
  • 189
3
for element in range(0,len(hello)):
      d[element] = hello[element].strip()
Hassan Anwer
  • 347
  • 2
  • 14
  • 3
    In addition to your code, please explain why your answer works and how it solves the problem. – buczek Sep 23 '16 at 19:41
2

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)

allonym
  • 1,408
  • 10
  • 18