正则表达式 – Python:从格式字符串中提取所有占位符
发布时间:2020-12-14 05:50:35 所属栏目:百科 来源:网络整理
导读:我必须’解析’格式字符串才能提取变量. 例如. s = "%(code)s - %(description)s" get_vars(s)'code','description' 我设法通过使用正则表达式来做到这一点: re.findall(r"%((w+))",s) 但我想知道是否有内置的解决方案(实际上Python会解析字符串以便对其
|
我必须’解析’格式字符串才能提取变量.
例如. >>> s = "%(code)s - %(description)s" >>> get_vars(s) 'code','description' 我设法通过使用正则表达式来做到这一点: re.findall(r"%((w+))",s) 但我想知道是否有内置的解决方案(实际上Python会解析字符串以便对其进行评估!). 解决方法
这似乎很有效:
def get_vars(s):
d = {}
while True:
try:
s % d
except KeyError as exc:
# exc.args[0] contains the name of the key that was not found;
# 0 is used because it appears to work with all types of placeholders.
d[exc.args[0]] = 0
else:
break
return d.keys()
给你: >>> get_vars('%(code)s - %(description)s - %(age)d - %(weight)f')
['age','code','description','weight']
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
