我试图使用re.sub()执行多个替换,除了我希望第一个替换是不同的.一个简单的方法是在第一次调用时使用count = 1运行两次re.sub(),但是因为re.sub()允许repl参数成为函数,所以我们可以在一次调用中实现这一点:

import re

def repl(matchobj):
    global first_sub
    if first_sub:
        first_sub = False
        print(f"Replacing '{matchobj.group()}' at {matchobj.start()} with ':)'")
        return ":)"
    else:
        print(f"Deleting '{matchobj.group()}' at {matchobj.start()}")
        return ""

text = "hello123 world456"
first_sub = True
text = re.sub(r"\d+", repl, text)

# Output:
#   Replacing '123' at 5 with ':)'
#   Deleting '456' at 14

不幸的是,这使用了global,这不是很好.有没有更好的办法?

推荐答案

使用迭代器,灵感来自Andrej:

import re

text = "hello123 world456"
text = re.sub(
    r"\d+",
    lambda _, i=iter([":)"]): next(i, ""),
    text
)
print(text)

Attempt This Online!

或为国家使用法令:

import re

text = "hello123 world456"
text = re.sub(
    r"\d+",
    lambda m, d={0: ":)"}: d.pop(0, ""),
    text
)
print(text)

Attempt This Online!

或者像你的,但有一个封闭:

import re

def repl():
    first_sub = True
    def repl(matchobj):
        nonlocal first_sub
        if first_sub:
            first_sub = False
            print(f"Replacing '{matchobj.group()}' at {matchobj.start()} with ':)'")
            return ":)"
        else:
            print(f"Deleting '{matchobj.group()}' at {matchobj.start()}")
            return ""
    return repl

text = "hello123 world456"
text = re.sub(r"\d+", repl(), text)
print(text)

Attempt This Online!

Python相关问答推荐

在函数内部使用eval(),将函数的输入作为字符串的一部分

韦尔福德方差与Numpy方差不同

根据另一列中的nan重置值后重新加权Pandas列

在Google Colab中设置Llama-2出现问题-加载判断点碎片时Cell-run失败

为什么抓取的HTML与浏览器判断的元素不同?

Stacked bar chart from billrame

为一个组的每个子组绘制,

从Windows Python脚本在WSL上运行Linux应用程序

在Python中计算连续天数

OpenGL仅渲染第二个三角形,第一个三角形不可见

用SymPy在Python中求解指数函数

如何使用matplotlib查看并列直方图

如何在信号的FFT中获得正确的频率幅值

我可以不带视频系统的pygame,只用于游戏手柄输入吗?''

有没有一种方法可以在朗肯代理中集成向量嵌入

递归链表反转与打印语句挂起

高效地计算数字数组中三行上三个点之间的Angular

Pandas 删除只有一种类型的值的行,重复或不重复

大Pandas 中的群体交叉融合

当lambda函数作为参数传递时,pyo3执行