Bug free version of string substitution

时间:2019-01-18 19:12:39

标签: python string algorithm substitution

I am trapped in a quite straight forward problem, but after some tweak, I simply cannot find an easy and efficient algorithm to do this.

So basically I have a string, which contains certain elements, for instance:

l = "test %1, %13, %14, %15"

And a map:

dict = {"%1": "%33", "%13": "%14", "%14", "%15", "%15": "%17"}

And I would like to do the following stuff:

for k in dict.keys():
    l = l.replace(k, dict[k])

So what I am expecting is:

l = "test %33, %14, %15, %17"

But apparently this is not feasible, since there are some conflict between keys and values. So the above code would output:

l = "test %33, %17, %17, %17"

Sorry for such native problem, but how should I solve this and get my expected output? Note that the length of each key/value is not fixed, so I cannot do something like:

m_idx = l_copy.find(key)
l = l[:m_idx] + dict[key] + l[m_idx+len(key):]

Because the length is not fixed, the above code is still buggy.

Am I clear on this? Any suggestion would be appreciated very much!

======= update

So all keys follow this pattern of %[0-9]+.

1 个答案:

答案 0 :(得分:6)

您可以将Default Configre.sub一起使用:

lambda

输出:

import re
l = "test %1, %13, %14, %15"
_dict = {"%1": "%33", "%13": "%14", "%14":"%15", "%15": "%17"}
new_l = re.sub('%\d+', lambda x:_dict[x.group()], l)

您可以使用'test %33, %14, %15, %17' 通过提供默认值来防止dict.get,如果密钥不出现在KeyError中:

_dict