cba*_*rdt 1 python string replace
我今天发现string.replace(str1, str2)Python 3 中的函数以及Python 2的行为并不像我本能地认为的那样:
$ 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 '
Run Code Online (Sandbox Code Playgroud)
我理解为什么会发生这种情况:replace一旦找到匹配,该函数会突然显示在上一次找到的匹配之后的第一个字符上,恰好n在我的情况下.因此,第二个(和第四个......)not永远不会被识别,因为缺少领先的空间.
替换字符串的标准方法是什么,以避免上面的反直觉行为(以便所有?not?s都大写)?
我知道我可以将我的字符串拆分为takens,将nots 更改为NOTs并重新组合它,但这不是我想要的.我怀疑Python中有适当的替换方式.
dsh*_*dsh 10
import re
s = re.sub(r"\bnot\b", "NOT", s)
Run Code Online (Sandbox Code Playgroud)
使用正则表达式来匹配单词边界,而不是尝试匹配单词之间的空格.