我有一个可变文本(在Python中),其中包含应该在文件中打印的文本,并且它有很多可变长度,大多数行的开头都有额外的空格。我只想删除这些空格。这是我使用的代码。
text = re.sub(r'(^s*)',r'',text,re.MULTILINE)
但是,仅擦除第一行的空格。其他一切都保持原样。谁能告诉我我做错了什么?
谢谢。
re.sub
的第四个参数是替换计数,而不是标志。
re.sub(pattern, repl, string, count=0, flags=0)
>>> re.MULTILINE
8
>>> print re.sub(r'(^s*)', '', ' an bn', re.MULTILINE)
a
b
使用关键字参数flags
。
>>> print re.sub(r'(^s*)', '', ' an bn', flags=re.MULTILINE)
a
b
顺便说一句,你不需要括号:
>>> print re.sub(r'^s*', '', ' an bn', flags=re.MULTILINE)
a
b
使用 str.lstrip
,您不需要正则表达式。
>>> print 'n'.join(map(str.lstrip, ' an bn'.splitlines()))
a
b
您可以这样做以避免正则表达式
text = 'n'.join([line.lstrip() for line in text.splitlines()])
这将拆分为行,剥离前导空格并再次组合回来。只是一个替代解决方案。我喜欢尽可能避免正则表达式。但其他人喜欢他们。
为什么不用lstrip
写入文件流呢?
file.write(content.lstrip())
假设你反复浏览你的文本,一行一行地写,它几乎是免费的。
避免正则表达式的性能提升可能不会超过代码可读性,除非您一直在处理大型文本。否则,使用正则表达式可能只会产生更容易理解的代码:
sample_text = " lorem ipsumn" * 10
beginning_whitespace = re.compile(r'^s+', flags=re.MULTILINE)
new_text = re.sub(beginning_whitespace, '', sample_text)
比,有点神秘,其他选项:
new_text = 'n'.join([line.lstrip() for line in sample_text.split('n')])
new_text = 'n'.join(map(str.lstrip, sample_text.splitlines()))