re.sub只替换前两个实例

dwk*_*wkd 4 python regex string replace

我用re.sub发现了这个有趣的问题:

import re

s = "This: is: a: string:"
print re.sub(r'\:', r'_', s, re.IGNORECASE) 

>>>> This_ is_ a: string:
Run Code Online (Sandbox Code Playgroud)

注意如何只替换前两个实例.似乎为标志添加[implicit]参数名称可以解决问题.

import re

s = "This: is: a: string:"
print re.sub(r'\:', r'_', s, flags=re.IGNORECASE) 

>>>> This_ is_ a_ string_
Run Code Online (Sandbox Code Playgroud)

我想知道是否有人可以解释它或它实际上是一个错误.

我之前遇到过这个问题,但缺少参数名称,string但从来没有因为flags字符串它通常会爆炸.

iCo*_*dez 7

第四个论点re.sub不是,flags但是count:

>>> import re
>>> help(re.sub)
Help on function sub in module re:

sub(pattern, repl, string, count=0, flags=0)
    Return the string obtained by replacing the leftmost
    non-overlapping occurrences of the pattern in string by the
    replacement repl.  repl can be either a string or a callable;
    if a string, backslash escapes in it are processed.  If it is
    a callable, it's passed the match object and must return
    a replacement string to be used.

>>>
Run Code Online (Sandbox Code Playgroud)

这意味着您需要明确地执行flags=re.IGNORECASE或以其他方式re.IGNORECASE将其视为参数count.

此外,该re.IGNORECASE标志等于2:

>>> re.IGNORECASE
2
>>>
Run Code Online (Sandbox Code Playgroud)

因此,通过count=re.IGNORECASE在您的第一个示例中执行操作,您告诉re.sub您只替换字符串中2出现的:内容.