0

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.

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1
def replaceVars(matchObj):
    return "{{{%s}}}" % matchObj.groups()[0]

c = r"\$(\w+)\s*"

s = "$who likes $what"

converted = re.sub(c, replaceVars, s)

3 Comments

This seems to be the best way right now. I am however struggling as I need to print the variable twice. It is more like {{{%s|something%s}}}
Like {{{who|somethingwho}}}, for example? Then just modify the replaceVars function.
cool - got it - just neede % ( matchObj.groups()[0], matchObj.groups()[0])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.