python-带有模式参考的正则表达式子

提问

可以说我有以下字符串:

s = """hi my name is 'Ryan' and I like to 'program' in "Python" the best"""

我想运行一个re.sub,它将以下字符串更改为:

"""hi my name is '{0}' and I like to '{1}' in "{2}" the best"""

这样可以保存内容,但是可以引用它,以便可以重新添加原始内容.

注意:我使用以下代码来获取所有带引号的项目,因此我将循环遍历以引用数字

items = re.findall(r'([\'"])(.*?)\1',s)

那么,如何使子程序识别数字实例,从而创建这种引用呢?

最佳答案

re.sub与回调一起使用:

>>> import itertools
>>> import re
>>> s = """hi my name is 'Ryan' and I like to 'program' in "Python" the best"""
>>> c = itertools.count(1)
>>> replaced = re.sub(r'([\'"])(.*?)\1', lambda m: '{0}{{{1}}}{0}'.format(m.group(1), next(c)), s)
>>> print(replaced)
hi my name is '{1}' and I like to '{2}' in "{3}" the best

使用itertools.count生成数字:

>>> it = itertools.count(1)
>>> next(it)
1
>>> next(it)
2
>>> next(it)
3