简体   繁体   English

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

[英]Python: How to replace string enclosed by certain characters

I want to replace a certain variable name in a mathematical expression while avoid to replace in function names. 我想在数学表达式中替换某个变量名称,同时避免在函数名称中替换。

For example following replacement of n : 例如,在替换n

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

My idea was to check whether the substr is enclosed by special characters ( ' ' , '(' , '*' , etc) at one side but I failed to put it in regex or python code. 我的想法是检查substr的一侧是否被特殊字符( ' ''(''*'等)括起来,但我未能将其放在正则表达式或python代码中。

Any ideas? 有任何想法吗?

Use word boundary( \\b ) 使用单词边界( \\b

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

According to the re module documentation : 根据re模块文档

\\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, ... 请注意,正式地,\\ b被定义为\\ w和\\ W字符之间的边界(反之亦然),或者\\ w与字符串的开头/结尾之间的边界,...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM