Skip to main content
 首页 » 编程设计

python之Python 中 string.replace() 的意外行为

2025年05月04日10shangdawei

我今天发现 Python 3 和 Python 2 中的函数 string.replace(str1, str2) 的行为并不像我本能地认为的那样:

$ python3 
Python 3.4.2 (default, Oct  8 2014, 10:45:20)  
[GCC 4.9.1] on linux 
Type "help", "copyright", "credits" or "license" for more information. 
>>> str = ' not not not not Cannot not not not '.replace(' not ', ' NOT ') 
>>> str 
' NOT not NOT not Cannot NOT not NOT ' 

我理解为什么会发生这种情况:显然 replace 函数一旦找到匹配项,就会继续处理上一个找到的匹配项之后的第一个字符,该匹配项恰好是 n就我而言。因此,第二个(和第四个...)not 永远不会被识别,因为缺少前导空格。

替换字符串以避免上述反直觉行为的标准方法是什么(以便所有 ␣not␣ 都大写)?

我知道我可以将我的字符串拆分成片段,将 not 更改为 NOT 并重新组合它,但这不是我想要的。我怀疑在 Python 中有一个合适的替代方法。

请您参考如下方法:

import re 
 
s = re.sub(r"\bnot\b", "NOT", s) 

使用正则表达式来匹配单词边界,而不是尝试匹配单词之间的空格。