Substitution with Hash Values
Bjorn Pettersen
BPettersen at NAREX.com
Fri Apr 19 17:52:36 EDT 2002
> From: Jeff Jones [mailto:jeff at jonesj.com]
>
> I am a long time perl user who is trying to get a grip on
> python. I really like what I have seen so far, but I have
> hit a little snag regarding substitution (like perl).
>
> I use html templates for all of my CGI programming, and
> everything that needs to be replaced is contained within
> double curly braces ( {{value}} ). In perl I use a hash to
> keep all of the variables that are going to replace the
> placeholders in the template, and replace them the following way:
>
> ....
> s/{{(.*?)}}/$hash{$1}/g;
> ....
>
> That substiution is accomplished as I read in the template file.
>
> Can anyone tell me how I might do this in python? I have
> tried many different ways, but none seem to work.
# create a dictionary with your substitutions
subst = { 'value1' : 123, 'value2' : 'hello world' }
# create the text with appropriate %(dict-key)s placeholders
txt = """
<body>
this is %(value1)d and this is %(value2)s
</body>
"""
# perform the substitutions
print txt % subst
Hth,
-- bjorn
More information about the Python-list
mailing list