[Python-Dev] PEP 292, Simpler String Substitutions

Martin Sjögren martin@strakt.com
Wed, 19 Jun 2002 10:33:11 +0200


On Wed, Jun 19, 2002 at 03:51:21AM -0400, Oren Tirosh wrote:
> On Wed, Jun 19, 2002 at 09:05:00AM +0200, Fredrik Lundh wrote:
> > Barry wrote:
> > 
> > > def birth(self, name):
> > >     country = self.countryOfOrigin['name']
> > >     return '${name} was born in ${country}'.sub()
> > 
> > now explain why the above is a vast improvement over:
> > 
> >     def birth(self, name):
> >         country = self.countryOfOrigin['name']
> >         return join(name, ' was born in ', country)
> 
> Assuming join = lambda *args: ''.join(map(str, args)) 
> 
> 1. Friendly for people coming from other languages (Perl/shell). Same r=
eason 
> why the != operator was added as an alternative to <>.
> 
> 2. Less quotes and commas for the terminally lazy.
> 
> 3. More flexible for data-driven use.  Either the template or the
> dictionary can be data rather than hard-wired into the code.

But what about

>>> '%(name)s was born in %(country)s' % {'name':'Guido',
  'country':'the Netherlands'}
'Guido was born in the Netherlands'
>>> name = 'Martin'
>>> country = 'Sweden'
>>> '%(name)s was born in %(country)s' % globals()
'Martin was born in Sweden'

What's the advantage of using ${name} and ${country} instead?


/Martin

-- 
Martin Sjögren
  martin@strakt.com              ICQ : 41245059
  Phone: +46 (0)31 7710870       Cell: +46 (0)739 169191
  GPG key: http://www.strakt.com/~martin/gpg.html