string interpolation for python

Yingjie Lan lanyjie at yahoo.com
Mon Apr 2 10:25:32 EDT 2012


> like this one ?

> 
> b = dict(name="Sue", job="SAS sharp-shooter")
> print "$b['name']$ works as b['job']"
> 
> Is it really easier to read that the following ?
> "{0} works as {1}".format(b['name'],b['job'])
> 
> In the case in which b is an object having "job" and "name" 
> attribute, the dynamic string will write
> 
> "$b.name$ works as $b.job$"
> instead of
> "{0}.name works as {0}.job".format(b)
> 


When you already have a dict, the dict-based
formatting would be nice.

>>> "%(name)s works as %(job)s"%b

If it you need to create a dict just for string

formatting, dynamic string would be nice.
Say your object has methods/properties
that fetch things from your database.

>>> class staff:
... at property
...def name(): return 'Peter'
...
>>> t = staff()
>>> vars(t)
{}
>>> t.name
'Peter'
>>> d"Staff name: $t.name$" #note the d"..." format
'Staff name: Peter'

Because of the d"..." format, it won't 
affect old ways of doing things one bit.
Allowing dynamic string wouldn't hurt 
a bit to anything that is already there.



More information about the Python-list mailing list