For example, I have the following string:
s = 'Name: @name, ID: @id'
Now I want to use re.sub()
to replace @name
and @id
. I know that I can use group to catch some string and then use '\g<index>'
or r'\index'
to use it.
But now I need use it as a dict key, I have this dict:
d = {'id': '20', 'name': 'Jon'}
And I wish I can get this:
s = 'Name: Jon, ID: 20'
Also I tried:
>>> re.sub('@(\w+)', d[r'\1'], s)
Traceback (most recent call last):
File "<input>", line 1, in <module>
KeyError: '\\1'
>>> re.sub('@(\w+)', d['\g<1>'], s)
Traceback (most recent call last):
File "<input>", line 1, in <module>
KeyError: '\\g<1>'
>>>