String interpolation question
Fernando Pérez
fperez528 at yahoo.com
Mon Apr 15 17:36:04 EDT 2002
Geoff Gerrietts wrote:
>> 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.
Thanks for your suggestions. Basically imagine having many arrays and needing
to generate output of the form (this is perl syntax, which for once is a
million times cleaner than python for _this_ problem):
print "$i arr1[$i]=$arr1[$i] arr2[$i]=$arr2[$i] arr3[$i]=$arr3[$i] ....\n";
To me, the above line is clear, unambiguous and requires zero contortions to
either write or read (by the coder). I have been so far unable to write in
python anything that comes anywhere within even shooting distance (with an
ICBM) of this (but I'd love to be proven wrong ;)
I appreciate your solutions, but they all require the building of artificial
structures or many temp variables. This makes for an ugly mess of the code if
I have say 15 arrays for which I need to generate output like the above, and
what annoys me is that a single well-interpolated line would do it (if such a
facility existed in our otherwise beloved snake).
Oh well, I guess I'll just write the ugly mess.
Thanks for the help though.
Cheers,
f.
More information about the Python-list
mailing list