我有一个从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)
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)
result = map(str.strip, hello)
Run Code Online (Sandbox Code Playgroud)