![](/img/trans.png)
[英]Remove/Replace all whitespaces from a multi-lines string, except newline characters
[英]is there a way to replace and remove lines of a multi-lines string
我正在尝试处理多行字符串,替换并删除一些行。 这是代码。
>>> txt
'1 Introduction\nPart I: Applied Math and Machine Learning Basics\n2 Linear Algebra'
>>> tmp = []
>>> for line in txt.splitlines():
... if re.findall('[0-9]', line):
... replaced = re.sub('[0-9]', '#', line)
... tmp.append(replaced)
>>> print(tmp)
['# Introduction', '# Linear Algebra']
虽然这段代码完成了我的工作,但我不确定它是否是最有效的方式。
有没有更有效的方法来做到这一点?
您可以将列表理解用于问题中提供的代码,这使得代码整洁。
[re.sub('[0-9]', '#', line) for line in txt.splitlines() if re.findall('[0-9]', line) ]
# Output
['# Introduction', '# Linear Algebra']
另外,就像@CertainPerformance在评论中提到的那样,因为你只想知道字符串中是否存在数字,最好使用search
而不是findall
。 然后你可以重新编写列表理解代码,
[re.sub('[0-9]', '#', line) for line in txt.splitlines() if re.search('[0-9]', line) ]
# Output
['# Introduction', '# Linear Algebra']
在我的机器上使用search
,我可以看到一个小的性能提升。
%%timeit 1000000
[re.sub('[0-9]', '#', line) for line in txt.splitlines() if re.search('[0-9]', line) ]
# 4.76 µs ± 53.7 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%%timeit 1000000
[re.sub('[0-9]', '#', line) for line in txt.splitlines() if re.findall('[0-9]', line) ]
# 5.21 µs ± 114 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.