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

79

我有一个从mysql数据库中获取的对象列表,其中包含空格。我希望删除这些空格,但是我使用的代码不起作用?

hello = ['999 ',' 666 ']

k = []

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

print k

2
或者修正数据库字段的类型;-) - ChristopheD
@ChristopheD:哪种数据库“字段”类型会强制保留前导空格?最好是修复开发人员和测试人员的问题。 - John Machin
1
@Johan Machin:我在第二个条目上错过了前导空格(判断得有点太快了,哎呀) - ChristopheD
7个回答

163

在Python中,字符串是不可变的(也就是说,它们的数据无法被修改),因此replace方法不会修改字符串,而是返回一个新字符串。您可以按照以下方式更正您的代码:

for i in hello:
    j = i.replace(' ','')
    k.append(j)
然而,更好的方法是使用列表推导式来实现您的目标。例如,以下代码使用 strip 从列表中的每个字符串中删除前导和尾随空格:
hello = [x.strip(' ') for x in hello]

21
加1分用于去除空格。减1分用于替换()中的空格。 - S.Lott
1
OP想要删除所有空格,而不仅仅是尾随空格,那么为什么对于replace(' ','')会有-1的评价呢?没有任何一个'strip'方法,更不用说其他内置的str方法可以完成这项工作(忽略Rube Goldbergs像''.join(s.split())这样的方法)。 - Mike DeSimone
啊,所以它不是使用空格来分隔千位、百万等的文本字段,因为它可能包含偶尔的关键字而被定义为文本?好的,我错过了这一点。 - Mike DeSimone
2
OP列表中的第二个元素有5个字符。前导和尾随空格。 - John La Rooy
1
由于示例未显示任何内部空格,因此我对删除内部空格持怀疑态度。 - S.Lott

21

列表推导式 [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

1
list(map(str.strip, hello)) 没有太多意义,因为 map 函数本身就返回一个列表。 - ChristopheD
4
在Python 3中,map函数不会返回一个列表。 - riza

13
result = map(str.strip, hello)

5
不需要使用 lambda,可以使用以下代码:result = map(str.strip(), hello)。然而,正如 @riza 所提到的,在 Python 3 中,map 函数返回一个迭代器而不是列表。因此最好的做法是 result = list(map(str.strip(), hello)) - amicitas
5
请注意,至少在Python 3中,您必须写成map(str.strip, mylist),而不是map(str.strip(), mylist) - William

7

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

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

4

假设您不想删除内部空格:

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]

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

3
除了您的代码外,请解释为什么您的答案有效以及它如何解决问题。 - buczek

2

replace()方法不会就地操作,您需要将其结果分配给某个变量。此外,为了更简洁的语法,您可以用一行代码取代您的for循环:hello_no_spaces = map(lambda x: x.replace(' ', ''), hello)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接