String interpolation question
Geoff Gerrietts
geoff at gerrietts.net
Mon Apr 15 16:50:40 EDT 2002
Quoting Fernando Pérez (fperez528 at yahoo.com):
...
> y=[5,6]
> i=1
>
> I want to print y[i]. The following fails:
>
> print '%(y[%(i)s])s' % locals()
>
> as does the simpler
>
> print '%(y[%(i)s])s' % locals()
>
> but I don't want that because in my real problem, the string is long and I
> don't want the dangers of positionally matched %s arguments.
Given your constraints, I think I'd prefer:
>>> print "%(val1)s" % { 'val1': y[i] }
Or if you insist on using locals() (a habit I find at least as
dangerous as positional arguments):
>>> z = y[i]
>>> print '%(z)s' % locals()
6
On the other hand, if you're looking at a long y and multiple values
of i (though your example provides no such hint), I'd prefer:
d = {}
for indx in range(len(y))
d['y_%d'%indx] = y[indx]
d.update(locals())
s = '%%(y_%d)s' % (i,)
print s % d
If none of these solutions seem to satisfy your needs, maybe you
should be a little more explicit about the problem domain. If one of
the requirements is that it be a one-liner, I'm not sure if I can
help.
On the other hand, if what you really want is to push the string
interpolation PEP, well, I'm just trying to help, not trying to argue
for or against a feature. As long as I don't hafta use the feature,
and I don't hafta work around the feature, I don't mind if the
feature's present.
Thanks,
--G.
--
Geoff Gerrietts "If life were measured by accomplishments,
<geoff at gerrietts net> most of us would die in infancy."
http://www.gerrietts.net/ --A.P. Gouthey
More information about the Python-list
mailing list