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
1
  • re.findall(r'%\((\w+)\)', s) works on the given example Commented May 30, 2021 at 3:33

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.