Substitution with Hash Values

Sean 'Shaleh' Perry shalehperry at attbi.com
Fri Apr 19 17:56:13 EDT 2002


On 19-Apr-2002 Jeff Jones wrote:
> 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.
> 

I presume you know that a dictionary in python is the equivalent of the perl
hash.

hash = {}
hash[key] = value
hash[other_key] = new_value
etc.

as for the substitution perl is a little better here because regex is part of
the language, but python can do it too with a little more typing.

import re
brace_re = re.compile(r'{{(.*?)}}')
....
match = brace_re.search(input)
if match:
    input = brace_re.sub(match.group(1), input)
# use input
....





More information about the Python-list mailing list