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

我有一个附加自 mysql 数据库的对象列表,其中包含空格。我希望删除空格,如下,但代码 IM 使用不工作?

hello = ['999 ',' 666 ']


k = []


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


print k
311144 次浏览
result = map(str.strip, hello)

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

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

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

hello = [x.strip(' ') for x in hello]

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

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

Place ()不能就地操作,您需要将其结果分配给某个对象。另外,为了获得更简洁的语法,您可以用一行程序 hello_no_spaces = map(lambda x: x.replace(' ', ''), hello)取代 for 循环

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

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]

列表内涵是最快的。

>>> 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()