English 中文(简体)
缩略语示意图模板中的变数
原标题:extract variables from python string template

对于铺设板模板,在模板显示中选取变量名称有干净的方法。

我实际上想能够把模板的分录写成一个案文领域,然后取代其他更为复杂的研究变量的变量。

例如,我将把用户输入模板输入一个可变的模板。

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

引言

 $who likes $what 

我需要一系列的变数名称,以便我能够把str改成像这样的东西。

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

或许还有更好的办法解决这一问题。

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

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

s = "$who likes $what"

converted = re.sub(c, replaceVars, s)
问题回答

i 不知道任何与模板有关的复制件,但你可以使用一种reg:

>>> 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.





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签