如何使用反向引用作为索引来通过列表进行替换?

How to use backreferences as index to substitute via list?

我有一个列表

fruits = ['apple', 'banana', 'cherry']

我喜欢用列表中的索引替换所有这些元素。我知道,我可以浏览列表并使用

之类的字符串替换
text = "I like to eat apple, but banana are fine too."
for i, fruit in enumerate(fruits):
    text = text.replace(fruit, str(i))

使用正则表达式怎么样?使用 \number 我们可以反向引用匹配项。但是

import re

text = "I like to eat apple, but banana are fine too."
text = re.sub('apple|banana|cherry', fruits.index(''), text)

不起作用。我收到 \x01 不在水果中的错误。但是</code>应该是指<code>'apple'

我对最有效的替换方法很感兴趣,但我也想更好地理解正则表达式。如何从正则表达式的反向引用中获取匹配字符串。

非常感谢。

使用正则表达式。

例如:

import re

text = "I like to eat apple, but banana are fine too."
fruits = ['apple', 'banana', 'cherry']

pattern = re.compile("|".join(fruits))
text = pattern.sub(lambda x: str(fruits.index(x.group())), text)
print(text)

输出:

I like to eat 0, but 1 are fine too.