Gerhard
Gerhard

Reputation: 2025

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.

Upvotes: 1

Views: 51

Answers (1)

user94559
user94559

Reputation: 60133

Check out the string.Formatter class:

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

Upvotes: 3

Related Questions