【发布时间】:2015-11-20 02:35:30
【问题描述】:
例如,我有以下字符串:
s = 'Name: @name, ID: @id'
现在我想用re.sub() 替换@name 和@id。我知道我可以使用 group 来捕获一些字符串,然后使用 '\g<index>' 或 r'\index' 来使用它。
但现在我需要将它用作字典键,我有这个字典:
d = {'id': '20', 'name': 'Jon'}
我希望我能得到这个:
s = 'Name: Jon, ID: 20'
我也试过了:
>>> 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>'
>>>
【问题讨论】:
标签: python regex python-3.x