我可以得到映射密钥吗



如果我在python中得到了字符串Hello %(firstname)s,我能在该字符串中得到预期的映射键吗?

一些伪代码示例:

>>> s = 'Hello %(name)s'
>>> s%{'name':'Ulf'}
'Hello Ulf'
>>> # The thing below is roughly what I want.
>>> s.get_map_keys()
['name']
>>> 'Hello %(name)s %(family)s'.get_map_keys()
['name', 'family']

注意:我知道这是老式格式,有更好的方法来生成字符串模板。但我正在分析现有的代码,无法控制字符串,我只需要处理它们,看看使用了哪些替换。

一个简单的正则表达式来检索它们:

import re
txt = 'Hello %(name)s %(family)s'
re.findall('%((.*?))', txt)

给出:

['name', 'family']

最新更新