Case insensitive version of string.Template?

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sat May 16 04:38:58 CEST 2009


En Fri, 15 May 2009 12:35:09 -0300, <python at bdurham.com> escribió:

> Using Python 2.6 or higher: Is there a way to configure
> string.Template() to ignore the case of matched identifiers?
> In other words, given the following Template string and
> dictionary where all keys are lowercase, is there a way to have
> my identifiers expanded based on their lowercase values?
> import string
> values = dict( name='John Doe', phone='999-555-1212' )
> output = string.Template( 'My name is $NAME and my phone is
> $Phone.' ).safe_substitute( values )

If you can guarantee the identifiers are all lowercase inside the  
dictionary:

class lowercase_dict(dict):
     def __getitem__(self, name):
         return dict.__getitem__(self, name.lower())

import string
values = lowercase_dict( name='John Doe', phone='999-555-1212' )
output = string.Template( 'My name is $NAME and my phone is $Phone.'  
).safe_substitute( values )

py> output
'My name is John Doe and my phone is 999-555-1212.'

If you cannot guarantee that, subclass string.Template:

class lowercase_template(string.Template):
   def safe_substitute(self, mapping=None, **kws):
     if mapping is None:
       mapping = {}
     m = lowercase_dict((k.lower(),v) for k,v in mapping.items())
     m.update(lowercase_dict((k.lower(),v) for k,v in kws.items()))
     return string.Template.safe_substitute(self, m)

-- 
Gabriel Genellina




More information about the Python-list mailing list