String interpolation question

Alex Martelli aleax at aleax.it
Mon Apr 15 17:20:26 EDT 2002


Fernando Pérez wrote:

> y=[5,6]
> i=1
> 
> I want to print y[i]. The following fails:

If you're a string-interpolation junky:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018

and particularly Skip Montanaro's variant (acknowledgedly inspired
by a post by Steve Majewski) may be to your taste.  With that:

        print "%$(y[i])s" % Eval()

works basically as you wish (I could quibble with a few details, but
it _would_ be quibbling).


Personally, I don't use string interpolation so widely.  If and when I
don't want by-position correspondence, I use explicit tags:

        print "%(nice_item)s" % {'nice_item': y[i]}

or actually (a question of tastes)

        print "%(nice_item)s" % dodict(nice_item=y[i])

with one of my favourite Python oneliners somewhere above:

def dodict(**kwargs): return kwargs


But again I'm quibbling.  The point is that I want to be able to i18n's
my format-strings, e.g via gettext.  That's what the explicit tags are
most useful for, IMHO -- allow natural language dependent reordering.

But I most definitely do NOT want general Python expressions in there,
which a translator might well accidentally botch.  I do want tags that
are easily recognizable as such, it's easy to explain that anything of
the form %(whateverishere)s stands for the runtime-determined
string "named" 'whateverishere' and should be used as part of the
whole format-string's translation in whatever place is appropriate in
the target natural-language.  By using a purpose-built dictionary on
the RHS of %, I control what values can be formatted at that point --
no accidents (if an unavailable tag is asked for I get an exception that
I can catch or propagate -- exactly as it should be).

For a particularly involved, perhaps multi-string message, I could also
build the dictionary once and use it on several % ops, I guess (never
happened yet, but maybe some day), letting each translated format
string get whatever subset of the available tagged values it needs.


For me, this does all I need.  In simple throw-away code I don't need
anything more than positional-correspondence of values.  In code of
some worth and weight, I want to keep the possibility of doing i18n when
needed without too much effort, and tagged values and the right
dict on the RHS of % provides very well for that. The idea of passing
locals() on the RHS is, well, something I think is nice to show a newbie
to wow him or her, but not something I'd ever use in my code...:-).


Alex




More information about the Python-list mailing list