您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python re.sub问题

Python re.sub问题

您可以在使用re.sub时指定回调,该回调可以访问组:http : //docs.python.org/library/re.html#text- munging

a = 'foo'
b = 'bar'

text = 'find a replacement for me [[:a:]] and [[:b:]]'

desired_output = 'find a replacement for me foo and bar'

def repl(m):
    contents = m.group(1)
    if contents == 'a':
        return a
    if contents == 'b':
        return b

print re.sub('\[\[:(.+?):\]\]', repl, text)

还注意到额外的吗?在正则表达式中。您要在此处进行非贪心匹配。

我了解这只是说明概念的示例代码,但是对于您给出的示例,简单的字符串格式更好。

python 2022/1/1 18:43:20 有286人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶