替换多个相似的字符串

时间:2016-03-30 14:26:56

标签: python string replace

我有下面的表达:

a = 'x11 + x111 + x1111 + x1'

我想替换以下内容:

from_ = ['1', '11', '111', '1111']
to = ['2', '22', '333', '3333']

因此获得以下结果:

anew = 'x22 + x333 + x3333 + x2'

如何使用Python执行此操作?

这是一个类似的问题:Python replace multiple strings。但是在我的情况下,如果我在问题中使用建议的anwsers,则替换的值会自行覆盖。因此,在提到的链接中,结果为'x22 + x222 + x2222 + x2'

1 个答案:

答案 0 :(得分:2)

只要您需要进行多值替换,就可以使用re.sub库(正则表达式)中的

re

re.sub接受函数的附加参数,在该函数中可以进行必要的更改。从文档

re.sub(pattern, repl, string, count=0, flags=0)
     

如果repl是一个函数,则每次非重叠都会调用它   发生模式。该函数采用单个匹配对象   参数,并返回   替换字符串

(强调我的)

这里的正则表达式很简单,即\d+表示您匹配所有数字组。

您可以使用以下代码段来获取所需的输出

import re

a = 'x11 + x111 + x1111 + x1'

def substitute(matched_obj):
    from_ = ['1', '11', '111', '1111']
    to = ['2', '22', '333', '3333']
    part = matched_obj.group(0)
    if part in from_:
        return to[from_.index(part)]
    return part

anew = re.sub(r'\d+',substitute,a)

执行程序后,anew的值将为x22 + x333 + x3333 + x2,这是预期的答案。 `