我有一个从mysql数据库中获取的对象列表,其中包含空格。我希望删除这些空格,但是我使用的代码不起作用?
hello = ['999 ',' 666 ']
k = []
for i in hello:
str(i).replace(' ','')
k.append(i)
print k
我有一个从mysql数据库中获取的对象列表,其中包含空格。我希望删除这些空格,但是我使用的代码不起作用?
hello = ['999 ',' 666 ']
k = []
for i in hello:
str(i).replace(' ','')
k.append(i)
print k
在Python中,字符串是不可变的(也就是说,它们的数据无法被修改),因此replace方法不会修改字符串,而是返回一个新字符串。您可以按照以下方式更正您的代码:
for i in hello:
j = i.replace(' ','')
k.append(j)
然而,更好的方法是使用列表推导式来实现您的目标。例如,以下代码使用 strip
从列表中的每个字符串中删除前导和尾随空格:hello = [x.strip(' ') for x in hello]
replace(' ','')
会有-1的评价呢?没有任何一个'strip'方法,更不用说其他内置的str方法可以完成这项工作(忽略Rube Goldbergs像''.join(s.split())
这样的方法)。 - Mike DeSimone列表推导式 [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
list(map(str.strip, hello))
没有太多意义,因为 map
函数本身就返回一个列表。 - ChristopheDresult = map(str.strip, hello)
lambda
,可以使用以下代码:result = map(str.strip(), hello)
。然而,正如 @riza 所提到的,在 Python 3 中,map
函数返回一个迭代器而不是列表。因此最好的做法是 result = list(map(str.strip(), hello))
。 - amicitasmap(str.strip, mylist)
,而不是map(str.strip(), mylist)
。 - William字符串方法返回修改后的字符串。
k = [x.replace(' ', '') for x in hello]
假设您不想删除内部空格:
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]
for element in range(0,len(hello)):
d[element] = hello[element].strip()
replace()方法不会就地操作,您需要将其结果分配给某个变量。此外,为了更简洁的语法,您可以用一行代码取代您的for循环:hello_no_spaces = map(lambda x: x.replace(' ', ''), hello)