String formatting char

Daniel Dittmar daniel.dittmar at sap.com
Tue Nov 20 06:05:37 EST 2001


"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.

Daniel






More information about the Python-list mailing list