String formatting char

Dale Strickland-Clark dale at riverhall.NOTHANKS.co.uk
Wed Nov 21 06:08:41 EST 2001


"Daniel Dittmar" <daniel.dittmar at sap.com> wrote:

>"Dale Strickland-Clark" <dale at riverhall.NOTHANKS.co.uk> wrote in message
>> The string formatting operator, %, is a mighty powerful beastie when
>> used in mapping mode if the map is an object of your own.
>[...]
>> Is there some way to alter the format escape character from % to
>> something else?
>
>The %(varname)s formatting can be implemented using the re.sub method:
>
>class FancyLookup (UserDict):
>    def replace (self, match):
>        key = match.group (1)
>        return self [key]
>
>lookup = FancyLookup ()
>result = re.sub (r'%\(([^)]+)\)s', lookup.replace, input)
>
>You could add a 'sub' method to your FancyLookup class, thus having the
>actual regular expression in only one place.
>

That's neat and gives you complete flexibility over the the
substitution syntax - you could use !var!, for example but assumes a
string substition.

Also it would be much slower than the built-in function.
--
Dale Strickland-Clark
Riverhall Systems Ltd



More information about the Python-list mailing list