有没有方法可以替换和删除多行字符串的行

2024-04-28 20:44:46 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

这段代码已经完成了我的工作,我不确定这是否是最有效的方法。在

我尝试了这个post和{a2},似乎它们的多重查找都不是针对多行的。在

有没有更有效的方法?在


Tags: and方法字符串retxt密码linemath
1条回答
网友
1楼 · 发布于 2024-04-28 20:44:46

你可以对你在问题中提供的代码使用列表理解,这样可以使代码整洁。在

[re.sub('[0-9]', '#', line) for line in txt.splitlines() if re.findall('[0-9]', line) ]

# Output 
['# Introduction', '# Linear Algebra']

另外,就像@CertainPerformance在评论中提到的,因为您只想知道字符串中是否存在一个数字,所以最好使用search,而不是{}。然后你可以重新编写列表理解代码为

^{pr2}$

在我的机器中使用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)

相关问题 更多 >