Python中string.replace()的意外行为
今天我发现Python 3和Python 2中的函数Python中string.replace()的意外行为,python,string,replace,Python,String,Replace,今天我发现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 no
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
永远不会被识别,因为前导空格丢失
替换字符串以避免上述违反直觉行为的标准方法是什么(以便所有␣不␣代码>s是否大写)
我知道我可以将字符串拆分为taken,将not
s更改为not
s并重新组合,但这不是我想要的。我怀疑Python中有一种合适的替换方法
import re
s = re.sub(r"\bnot\b", "NOT", s)
使用正则表达式匹配单词边界,而不是尝试匹配单词之间的空格
使用正则表达式匹配单词边界,而不是尝试匹配单词之间的空格。为什么不使用str='not'。替换('not','not')
?不能只执行'str='not'。替换('not','not')'?不替换为NOTYes,str.replace
不重叠。为什么不使用带有单词边界的正则表达式,以及re.sub
?@Ahsanul Haque:我不能这样做,因为不能
更改为不能
@roymustang86:在本例中,这会起作用,但是失败,例如,not nothing
,因为nothing
也会被更改。为什么您不使用str='not'。替换('not','not')
?您不能只执行'str='not not'。替换('not','not')`?不替换为NOTYes,str.replace
不重叠。为什么不使用带有单词边界的正则表达式,以及re.sub
?@Ahsanul Haque:我不能这样做,因为不能
更改为不能
@roymustang86:在本例中,这会起作用,但在没有
的情况下失败,因为没有
也会被更改