String formatting with two dictionaries?

Peter Hansen peter at engcorp.com
Tue Oct 9 06:18:49 CEST 2001


Chris Liechti wrote:
> 
> Carsten Gaebler <clpy at snakefarm.org> wrote in
> news:3BC166F4.5E7FAB08 at snakefarm.org:
> > Given a string
> > s = "%(foo)s %(spam)s"
> > and two dictionaries
> > d1 = {"foo": "bar"}
> > d2 = {"spam": "eggs"}
> >
> > how would you apply d1 and d2 to s without modifying or explicitly
> > copying one of the dicts? >
> 
> s = ("%(foo)s %%(spam)s" % d1) % d2
> 
> use two "%" for variables that are in the second dict.

Neat.  Note of course that this requires everything which
has only a single % to be in the first dictionary, and 
everything with %% to be in the second.  Might be what 
was wanted... or maybe the OP won't like that either...

-Peter



More information about the Python-list mailing list