Substitution with Hash Values

holger krekel pyth at devel.trillke.net
Fri Apr 19 18:05:14 EDT 2002


On Fri, Apr 19, 2002 at 04:48:12PM -0500, 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;
> 	....
> 

my try (although my perl knowledge is at best dusty):

	 def value(match):
	    return dict[match.group(1)]
	
	 regex_key=re.compile('\{\{(.*?)\}\}')

	 regex_key.subn(value, str)

you might like to write that in one line

	 re.sub('\{\{(.*?)\}\}',lambda x: dict[x.group(1)], str)

where dict is a dictionary. As you see you can pass functions
as a 'substitution pattern'. This function operates on the
match object. 

is this what you want?

regards,

	holger






More information about the Python-list mailing list