python - 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'
单词之间和行尾的空格不应该匹配,只能在开头匹配。此外,无需匹配标签。非常感谢帮助
解决方案
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'
]
此处使用的模式'^ +'
将搜索和替换空格,只要它们位于字符串的开头。
推荐阅读
- python - 点击时tkinter显示框架
- oracle - 触发 + 变异错误 + 级联更新
- oracle - 在多个 pl sql 块上使用条件
- c++ - 事件 QComboBox 到自定义 QLineEdit
- django - Django 将迁移问题更改为新的 Postgres DB
- mysql - mysql - 如何在 JOIN 查询后在结果表中显示连接表的主键?
- alexa - Alexa无需“询问”技能即可调用自定义意图
- sql - 查找 column1 与 column2 匹配的行(可能在另一行中)
- php - php类常量或类构造错误?
- typed-racket - 你应该如何在 Typed Racket 的 letrec 中键入注解相互递归函数?