Python:从列表对象中删除空格

Har*_*pal 48 python list

我有一个从mysql数据库附加的对象列表,并包含空格.我希望删除下面的空格,但我使用的代码不起作用?

hello = ['999 ',' 666 ']

k = []

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

print k
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 103

Python中的字符串是不可变的(意味着它们的数据不能被修改),因此replace方法不会修改字符串 - 它返回一个新字符串.您可以按如下方式修复代码:

for i in hello:
    j = i.replace(' ','')
    k.append(j)
Run Code Online (Sandbox Code Playgroud)

然而,实现目标的更好方法是使用列表理解.例如,以下代码使用以下命令从列表中的每个字符串中删除前导和尾随空格strip:

hello = [x.strip(' ') for x in hello]
Run Code Online (Sandbox Code Playgroud)

  • +1为条带.-1表示替换('','') (11认同)
  • OP列表中的第二个元素有5个字符.领先和尾随空间 (2认同)

riz*_*iza 11

列表理解[num.strip() for num in hello]是最快的.

>>> 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
Run Code Online (Sandbox Code Playgroud)

  • @ChristopheD:在 Python 3 中,map 不返回列表。 (4认同)

yed*_*tko 7

result = map(str.strip, hello)
Run Code Online (Sandbox Code Playgroud)

  • 没有必要使用`lambda`; 相反,你可以使用:`result = map(str.strip(),hello)`.但是,正如@riza所提到的,在Python 3中,map返回一个迭代器而不是一个列表.所以最好的做法是`result = list(map(str.strip(),hello))`. (3认同)
  • 请注意(至少在Python 3中),您必须说`map(str.strip,mylist)`而不是`map(str.strip(),mylist)`。 (2认同)

Ign*_*ams 5

字符串方法返回修改后的字符串。

k = [x.replace(' ', '') for x in hello]
Run Code Online (Sandbox Code Playgroud)