Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get keys from template

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

like image 230
Yann Avatar asked Oct 23 '12 19:10

Yann


1 Answers

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.

like image 104
Roman Imankulov Avatar answered Sep 29 '22 01:09

Roman Imankulov