【问题标题】:Python: extract all placeholders from format stringPython:从格式字符串中提取所有占位符
【发布时间】:2013-09-27 10:02:33
【问题描述】:

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

例如

>>> s = "%(code)s - %(description)s"
>>> get_vars(s)
'code', 'description'

我设法通过使用正则表达式来做到这一点:

re.findall(r"%\((\w+)\)", s)

但我想知道是否有内置的解决方案(实际上 Python 会解析字符串以对其进行评估!)。

【问题讨论】:

  • 我建议您改用新的 python 3 字符串格式,其中string.Formatter 和解析模块:github.com/r1chardj0n3s/parse 都可用。
  • 请给 -1 一个理由:它会帮助我改进我的问题!

标签: regex parsing python-2.x string-formatting


【解决方案1】:

这似乎很好用:

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

【讨论】:

  • +1 这当然是一个很好的解决方案,但仍然使用了一个“技巧”;没有原生解决方案吗?
  • 我怀疑标准库中有什么东西;您可以查看 CPython 源代码,了解 % 运算符是如何为 basestring 实现的,以及它是否可以从 basestring 本身外部重用。如果不是,原则上任何第 3 方解决方案都应该像这里的这个技巧一样脆弱(或可靠)。
猜你喜欢
  • 2019-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-15
  • 1970-01-01
  • 1970-01-01
  • 2019-09-22
  • 2016-01-07
相关资源
最近更新 更多