简体   繁体   中英

extract variables from python string template

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.

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.

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

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

s = "$who likes $what"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM