0

对于 python 字符串模板,有一种干净的方法可以提取模板字符串中的变量名。

我实际上希望能够将模板字符串写入文本字段,然后将变量替换为其他看起来更复杂的变量。

因此,例如,我会将用户输入的模板放入变量中

t = Template(( request.POST['comment'] ))

评论字符串可能

'$who likes $what'

我需要一个变量名称数组,以便可以将字符串转换为类似

{{{who}}} likes {{{what}}}

也许还有更好的方法来解决这个问题。

4

2 回答 2

3

我不知道任何与模板相关的 api,但您可以使用正则表达式:

>>> import re
>>> rx = re.compile(r'\$(\w+)')
>>> rx.sub(r'{{{\1}}}', '$who likes $what')
'{{{who}}} likes {{{what}}}'

的第一个参数rx.sub()替换第二个参数中每次出现的变量,并\1替换为变量的名称。

于 2012-04-15T01:09:56.440 回答
1
def replaceVars(matchObj):
    return "{{{%s}}}" % matchObj.groups()[0]

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

s = "$who likes $what"

converted = re.sub(c, replaceVars, s)
于 2012-04-15T01:08:37.500 回答