【问题标题】:Extracting keys from %-style format string template从 %-style 格式字符串模板中提取键
【发布时间】:2021-05-30 03:30:35
【问题描述】:

我有一个使用% 样式格式的字符串,我想从中提取其键:

s = 'Hello %(name)s, you are %(age)d years old!'

我想做一些事情,例如:

from string import Formatter
keys = {key for _, k, _, _ in Formatter().parse(s)}
print(keys)
# ('name', 'age')

但是,% 样式格式不支持此功能;还有其他方法吗?我也已经读过:

  1. How can I extract keywords from a Python format string?
  2. Get keys from template

【问题讨论】:

  • re.findall(r'%\((\w+)\)', s) 适用于给定的示例

标签: python


【解决方案1】:

re.findall可以轻松拿到钥匙:

s = 'Hello %(name)s, you are %(age)d years old!'
keys = re.findall(r'%\((.*?)\)', s)
print(keys)  # ['name', 'age']

不过我不确定你想用这些键做什么。

【讨论】:

    【解决方案2】:

    只是为了好玩,但不建议用于生产:

    >>> s = 'Hello %(name)s, you are %(age)d years old!'
    >>> from collections import defaultdict
    >>> d = defaultdict(float)
    >>> s % d
    'Hello 0.0, you are 0 years old!'
    >>> d.keys()
    >>> for k in d:
    ...     print(k)
    ...
    name
    age
    >>>
    
    

    【讨论】:

      猜你喜欢
      • 2021-12-21
      • 1970-01-01
      • 2014-11-17
      • 2017-02-10
      • 2012-07-16
      • 1970-01-01
      • 2011-10-08
      • 1970-01-01
      • 2016-10-15
      相关资源
      最近更新 更多