这里是列表中字符串的示例
item_s=["hello - this","is - a","sample - task","i","want - to","do"]
我可以有这样的输出:
item_s=["hello-this","is-a","sample-task","i","want-to","do"]
这是我尝试修剪空格的代码,但显示错误
amount=list(df["Price Range"])
def add_commas(s):
s1, s2 = s.split('-')
def process(s_part):
n, tmp_s = len(s_part), []
for i in range(n):
if i and not i % 3:
tmp_s.append(',')
tmp_s.append(s_part[n - i - 1])
return ''.join(tmp_s[::-1])
return process(s1) + '-' + process(s2)
def main():
amount=list(df["Price Range"])
return [add_commas(v) for v in amount]
main
答案 0 :(得分:2)
您可以在列表推导式中使用 replace()
:
item_s=["hello - this","is - a","sample - task","i","want - to","do"]
item_s=[item.replace(" ", "") for item in item_s]
print(item_s)
答案 1 :(得分:2)
使用列表推导式,您可以遍历列表中的项目,然后用 str.replace()
替换空格:
item_s = ["hello - this", "is - a", "sample - task", "i", "want - to", "do"]
item_s = [s.replace(' ', '') for s in item_s]
print(item_s)
输出
['hello-this', 'is-a', 'sample-task', 'i', 'want-to', 'do']
或者您可以就地更新:
for i, s in enumerate(item_s):
item_s[i] = s.replace(' ', '')
并替换所有形式的空格,其中可能包括空格、制表符、换行符等,您可以使用正则表达式:
import re
item_s = [re.sub(r'\s', '', s) for s in item_s]
答案 2 :(得分:1)
当然可以,这是代码:)
您可以使用 for 循环并用空字符串替换所有空格:
item_s=["hello - this","is - a","sample - task","i","want - to","do"]
for s in range(len(item_s)):
item_s[s] = item_s[s].replace(" ", "")
print(item_s)