Reputation: 4752
For python string template is there a clean way to extract the variable names in the template string.
I actually want to to be able to write template stings into a textfield on and then substitue the variables for other more complex looking variables.
So for example I would get user inputted template into a variable
t = Template(( request.POST['comment'] ))
the comment string maybe
'$who likes $what'
I need an array of the variables names so I can convert the string to something like
{{{who}}} likes {{{what}}}
Maybe there is also a better way to approach this.
Upvotes: 0
Views: 1042
Reputation: 46892
i don't know of any template-related api, but you can use a regexp:
>>> import re
>>> rx = re.compile(r'\$(\w+)')
>>> rx.sub(r'{{{\1}}}', '$who likes $what')
'{{{who}}} likes {{{what}}}'
the first argument to rx.sub()
replaces each occurrence of a variable in the second argument, with \1
being replaced by the name of the variable.
Upvotes: 3
Reputation: 24788
def replaceVars(matchObj):
return "{{{%s}}}" % matchObj.groups()[0]
c = r"\$(\w+)\s*"
s = "$who likes $what"
converted = re.sub(c, replaceVars, s)
Upvotes: 1