使用字典替换子字符串的所有实例

时间:2018-12-19 23:30:25

标签: python regex pattern-matching

我知道有一种方法可以替换所有与某种模式匹配的实例,例如:re.sub(r'x', 'y', string)

但是有没有办法用与字典中最后一个字符的值相对应的值替换所有#a#b之类的实例?

dict = {'a': '1', 'b': 2', ... }

所以abc#bcd#ae变成abc2cd1e,等等。

3 个答案:

答案 0 :(得分:3)

re.sub的第二个参数(替换所有匹配项)可以是可调用的。如果是这样,则为每个匹配项使用单个参数match对象调用,并将其结果替换为字符串。因此,您可以执行以下操作:

d = {'a': 'A', 'b': 'B'}
s = '#a #b and #c'
def replace_it(m):
    return d.get(m.group('key'), m.group(0))
print re.sub('#(?P<key>[a-zA-Z]+)', replace_it, s)

答案 1 :(得分:1)

您可以替换字符串中找到的所有匹配项:

mydict = {'a':'1', 'b':'2'}
mystr = '#a#b'
for k, v in mydict.items():
    mystr = mystr.replace('#' + k, v)

答案 2 :(得分:0)

如果您知道要替换的确切内容,则不需要正则表达式。当您寻找模式时,这些功能更适合您,而不是精确匹配。 string.replace应该可以解决这个问题。

string = "a#acbb#bd"
dictionary = {'a':'1', 'b':'2'}
newstring1 = string.replace('#a', dictionary['a'])
newstring = newstring1.replace('#b', dictionary['b'])
print(newstring)
>>>a1cbb2d