首页 > 解决方案 > Python:匹配并替换每行开头的所有空格

问题描述

我需要像这样转换文本:

' 1 white space before string'
'  2 white spaces before string'
'   3 white spaces before string'

成一个:

' 1 white space before string'
'  2 white spaces before string'
'   3 white spaces before string'

单词之间和行尾的空格不应该匹配,只能在开头匹配。此外,无需匹配标签。非常感谢帮助

标签: pythonregex

解决方案


re.sub与执行实际替换的回调一起使用:

import re

list_of_strings = [...]

p = re.compile('^ +')
for i, l in enumerate(list_of_strings): 
    list_of_strings[i] = p.sub(lambda x: x.group().replace(' ', ' '), l)

print(list_of_strings)
[' 1 white space before string',
 '  2 white spaces before string',
 '   3 white spaces before string'
]

此处使用的模式'^ +'将搜索和替换空格,只要它们位于字符串的开头。


推荐阅读