gpt4 book ai didi

python - re.sub 仅替换前两个实例

转载 作者:太空狗 更新时间:2023-10-30 02:19:52 26 4
gpt4 key购买 nike

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

import re

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

>>>> This_ is_ a: string:

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

import re

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

>>>> This_ is_ a_ string_

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

我以前遇到过这个问题,因为缺少参数名称 string 但从来没有遇到过 flags 和 string 它通常会爆炸。

最佳答案

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.

>>>

这意味着您需要显式执行 flags=re.IGNORECASE 否则 re.IGNORECASE 将被视为 count 的参数.

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

>>> re.IGNORECASE
2
>>>

因此,通过在您的第一个示例中执行 count=re.IGNORECASE,您告诉 re.sub 仅替换 2 次出现的 : 在字符串中,它确实这样做了。

关于python - re.sub 仅替换前两个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27026228/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com