How can I find all placeholders for str.format in a python string using a regex? [duplicate]

Another possibility is to use Python’s actual Formatter itself to extract the field names for you:

>>> import string
>>> s = "{foo} spam eggs {bar}"
>>> string.Formatter().parse(s)
<formatteriterator object at 0x101d17b98>
>>> list(string.Formatter().parse(s))
[('', 'foo', '', None), (' spam eggs ', 'bar', '', None)]
>>> field_names = [name for text, name, spec, conv in string.Formatter().parse(s)]
>>> field_names
['foo', 'bar']

or (shorter but less informative):

>>> field_names = [v[1] for v in string.Formatter().parse(s)]
>>> field_names
['foo', 'bar']

Leave a Comment