我有一个字符串列表,如果每个项目都超过一个空格,则需要修剪所有空格。
original = ['1 0 1', 'how is it \n going?', 'hey how are you today?', '0']
without_spaces = [item.replace('\s+', ' ', regex=True) for item in original]
我的预期输出是:
print(original)
['1 0 1', 'how is it going?', 'hey how are you today?', '0']
对此有何想法?
答案 0 :(得分:2)
您可以将re.sub()
用于此目的:
import re
original = ['1 0 1', 'how is it \n going?', 'hey how are you today?', '0']
without_spaces = [re.sub('\s+', ' ', item) for item in original]
print(without_spaces)
输出将是:
['1 0 1', 'how is it going?', 'hey how are you today?', '0']
答案 1 :(得分:1)
' '.join(mystring.split())
这将按单词拆分,并使用" "
将它们重新连接为单个字符串。
另一种方法是:
import re
re.sub('\s+', ' ', mystring).strip()
希望这会有所帮助。祝你好运。
答案 2 :(得分:1)
类似的事情应该起作用
import re
original = ['1 0 1', 'how is it \n going?', 'hey how are you today?', '0']
without_spaces = [re.sub("\s+", " ", item) for item in original]
print(without_spaces)