0

I have a string using the % style formatting that I would like to extract its keys from:

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

I would like to do something such as:

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

However, this is unsupported with % style formatting; is there another way? I've also already read:

  1. How can I extract keywords from a Python format string?
  2. Get keys from template
pstatix
  • 3,611
  • 4
  • 18
  • 40

2 Answers2

3

Well re.findall can easily get the keys:

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

I'm not sure exactly what you want to do with these keys though.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

Just for fun but not recommended for production use:

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