简体   繁体   English

从python字符串模板中提取变量

[英]extract variables from python string template

For python string template is there a clean way to extract the variable names in the template string. 对于python字符串模板,有一种干净的方法可以提取模板字符串中的变量名称。

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: 我不知道任何与模板相关的api,但是您可以使用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. rx.sub()的第一个参数替换第二个参数中每次出现的变量,用\\1替换变量名。

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

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

s = "$who likes $what"

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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