I would like to get a list of all possible keyword arguments a string template might use in a substitution.
Is there a way to do this other than re?
I want to do something like this:
text="$one is a $lonely $number."
keys = get_keys(text)
# keys = ('one', 'lonely', 'number')
I'm writing a simple Mad-lib-like program, and I want to perform template substitution with either string.format or Template strings. I'd like to write the 'story' and have my program produce a template file of all the 'keywords' (nouns, verbs, etc.) that a user would need to produce. I know I can do this with regular expressions, but I was wondering if there is an alternative solution? I'm open to alternatives to string.format and string template.
I thought there would be solution to this, but I haven't come across it in a quick search. I did find this question, reverse template with python, but it's not really what I'm looking for. It just reaffirms that this can be done with re
.
EDIT:
I should note that $$
is an escape for '$', and is not a token I want. $$5
should render to "$5".
If it's okay to use string.format
, consider using built-in class string.Formatter
which has a parse()
method:
>>> from string import Formatter
>>> [i[1] for i in Formatter().parse('Hello {1} {foo}') if i[1] is not None]
['1', 'foo']
See here for more details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With