Gerhard Gerhard - 2 months ago 8
Python Question

What is the easiest way to get a list of the keywords in a string?

For example:

str = 'abc{text}ghi{num}'


I can then do

print(str.format(text='def',num=5))
> abcdefghi5


I would like to do something like

print(str.keywords) # function does not exist
> ['text','num']


What is the easiest way to do this? I can search character-by-character for
{
and
}
but I wonder if there a built-in python function?

Thank you.

Answer

Check out the string.Formatter class:

>>> import string
>>> text = 'abc{text}ghi{num}'
>>> [t[1] for t in string.Formatter().parse(text)]
['text', 'num']
Comments