首页 > 解决方案 > 有没有办法替换和删除多行字符串的行

问题描述

我正在尝试处理多行字符串,替换和删除一些行。这是代码。

>>> 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']

这段代码虽然完成了我的工作,但我不确定它是否是最有效的方法。

我试过这篇文章文档,似乎他们的多个查找都不是多行的。

有没有更有效的方法来做到这一点?

标签: pythonregex

解决方案


您可以对问题中提供的代码使用列表推导,这使代码整洁。

[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)

推荐阅读