Python:如何替换由某些字符括起来的字符串

2024-09-28 21:28:52 发布

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

我想在数学表达式中替换某个变量名,而避免在函数名中替换。在

例如,以下替换n

sin(2 pi*n d)" -> "sin(2 pi*REPL d)但不是:siREPL(2 pi*REPL d)

我的想法是检查substr是否被特殊字符(' ''(''*'等)括在一起,但我没有将其放入regex或python代码中。在

有什么想法吗?在


Tags: 函数代码表达式pi数学sinreplregex
1条回答
网友
1楼 · 发布于 2024-09-28 21:28:52

使用词边界(\b

>>> import re
>>> re.sub(r'\bn\b', 'REPL', 'sin(2 pi*n d)')
'sin(2 pi*REPL d)'

根据^{} module documentation

\b

Matches the empty string, but only at the beginning or end of a word. A word is defined as a sequence of alphanumeric or underscore characters, so the end of a word is indicated by whitespace or a non-alphanumeric, non-underscore character. Note that formally, \b is defined as the boundary between a \w and a \W character (or vice versa), or between \w and the beginning/end of the string, ...

相关问题 更多 >