>> get_vars(s) 'code', 'description' 我-6ren">
gpt4 book ai didi

regex - python : extract all placeholders from format string

转载 作者:行者123 更新时间:2023-12-03 18:24:41 25 4
gpt4 key购买 nike

我必须“解析”格式字符串才能提取变量。

例如。

>>> 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']

关于regex - python : extract all placeholders from format string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19048017/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com