string interpolation for python
Duncan Booth
duncan.booth at invalid.invalid
Mon Apr 2 06:19:54 EDT 2012
Yingjie Lan <lanyjie at yahoo.com> wrote:
> Both template based and dict-based formatting require writing the
> identifier three times:
>>>> name = 'Peter'
>>>> "Are you %(name)s"%{'name':name}
> ÿ
> If dynamic string is used:
>>>> "Are you $name$?"
> Template:
>>>> Template("Are you $name?").substitute(name=name)
> It is three to one in compactness, what a magic 3!
You can avoid the duplication fairly easily:
>>> name='Peter'
>>> 'Are you {name}?'.format(**vars())
'Are you Peter?'
though if you're doing that it would be better to limit the scope to a
specific namespace.
--
Duncan Booth http://kupuguy.blogspot.com
More information about the Python-list
mailing list