替换多个相似的字符串 [英] Replacing multiple similar strings
问题描述
我有以下表达:
a = 'x11 + x111 + x1111 + x1'
我想替换以下内容:
from_ = ['1', '11', '111', '1111']to = ['2', '22', '333', '3333']
因此得到以下结果:
anew = 'x22 + x333 + x3333 + x2'
如何使用 Python 执行此操作?
这是一个类似的问题:Python 替换多个字符串.但是,在我的情况下,如果我在问题中使用建议的 anwsers,则替换的值会被自己覆盖.因此,在提到的链接中,结果是 'x22 + x222 + x2222 + x2'
re.sub
来自 re
库(正则表达式)可以在您需要进行多值替换时使用.
re.sub
接受函数的附加参数,您可以在该函数中进行必要的更改.来自文档
re.sub(pattern, repl, string, count=0, flags=0)
如果 repl
是一个函数,它会为每一个非重叠的模式的出现.该函数接受一个单个匹配对象参数,并返回替换字符串.
(强调我的)
这里的正则表达式很简单,即 \d+
这意味着您正在匹配所有数字组.
您可以使用以下代码片段来获得所需的输出
导入重新a = 'x11 + x111 + x1111 + x1'定义替代(matched_obj):from_ = ['1', '11', '111', '1111']to = ['2', '22', '333', '3333']部分=matched_obj.group(0)如果参与 from_:返回到[from_.index(part)]退货部分anew = re.sub(r'\d+',substitute,a)
执行程序后,anew
的值将是 x22 + x333 + x3333 + x2
这是预期的答案.`
I have the folowing expression:
a = 'x11 + x111 + x1111 + x1'
and I would like to replace the following:
from_ = ['1', '11', '111', '1111']
to = ['2', '22', '333', '3333']
and therefore obtain the following result:
anew = 'x22 + x333 + x3333 + x2'
How can I do this using Python?
This is a similar question to: Python replace multiple strings. However in my case the replaced values are being overwiten by themselves if I use the suggested anwsers in the question. Hence, in the metioned link the result is 'x22 + x222 + x2222 + x2'
re.sub
from the re
library (regex) can be used whenever you need to do multi-value replacements.
re.sub
takes in the additional argument of a function, in that function you can make the necessary change. From the documentation
re.sub(pattern, repl, string, count=0, flags=0)
If
repl
is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string.
(emphasis mine)
The regex here is simple, i.e, \d+
which implies that you are matching all the groups of digits.
You can utilize the following code snippet to get your desired output
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)
After executing the program the value of anew
will be x22 + x333 + x3333 + x2
which is the expected answer.
`
这篇关于替换多个相似的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!