Alternative dictionary output format?

Evan Simpson evan at tokenexchange.com
Fri Jun 4 12:51:09 EDT 1999


I don't know if this is 100% bulletproof, but it has simple behavior:

pctsub = re.compile('%(?!%*\()').sub
def pfstr(s, pctsub = pctsub):
  '''Double all '%' except those leading up to a '(', for dict formatting'''
  return pctsub('%%', s)

>>> pfstr("%(href)s/foo/bar?x=%m&y=%n") % {'href': 'baz' }
'baz/foo/bar?x=%m&y=%n'

All percent signs pass unharmed, except for those in front of a left paren.
In that case '%(href)' => 'baz', '%%(href)' => '%(href)', '%%%(href)' =>
'%baz', etc.

Jeff Epler wrote in message ...
On Fri, 04 Jun 1999 14:55:42 GMT, rael at my-deja.com
<rael at my-deja.com> wrote:
>s = "%(href)s/foo/bar?x=%m&y=%n"

(he wants to only substitute the %(href) and not the rest)

s = "%(href)s/foo/bar?x=%%m&y=%%n"

i.e., double the percents you want to have not interpolated at this stage
of the game.

A clever regular expression might be able to do this for you, but the way
to write it 100% bulletproof escapes me.







More information about the Python-list mailing list