我有一个字符串列表,如果它超过一个空格,我需要为每个项目修剪所有空格。
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']
对此有什么想法吗?
最佳答案
为此,您可以使用 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']
关于python - 如何从字符串列表中删除空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58512236/