![](/img/trans.png)
[英]Remove whitespaces from beginning and end of each line in a file in python
[英]Python: match and replace all whitespaces at the beginning of each line
我需要这样转换文本:
' 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'
]
此处使用的模式为'^ +'
,只要空格位于字符串的开头,它们就会搜索并替换空格。
如果您知道空格只是前导空格,则可以执行以下操作:
l = ' ' * (len(l) - len(l.lstrip())) + l.lstrip()
虽然不是最有效的。 这样会更好一些:
stripped = l.strip()
l = ' ' * (len(l) - len(stripped)) + stripped
print(l)
它是这样做没有一种方式re
开销。
例如:
lines = [
' 1 white space before string',
' 2 white spaces before string',
' 3 white spaces before string',
]
for l in lines:
stripped = l.strip()
l = ' ' * (len(l) - len(stripped)) + stripped
print(l)
输出:
1 white space before string
2 white spaces before string
3 white spaces before string
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.