String interpolation question
Geoff Gerrietts
geoff at gerrietts.net
Mon Apr 15 19:23:28 EDT 2002
Quoting Fernando Pérez (fperez528 at yahoo.com):
> Geoff Gerrietts wrote:
>
> 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 see where you're coming from here, and I don't argue too strenuously
with it -- in this case the perl syntax doesn't bite back, which is a
pleasant place to find yourself. ;)
I would solve this in one of several ways, depending on which way
struck me at the time of writing. I think the most likely solution
would be something like:
>>> pieces = ["%d" %(i,)]
>>> for x in range(1,maxarray+1):
>>> arr = "arr%d" % x
>>> val = locals()[arr][i]
>>> pieces.append("%(arr)s[%(i)d]=%(val)s}"%locals())
>>> print " ".join(pieces)
Because of who I am, and how I code, I think it's more likely that it
would turn up like:
>>> pieces = ["%d" %(i,)]
>>> for x in range(1,maxarray+1):
>>> arr = "arr%d" % x
>>> val = locals()[arr][i]
>>> bit = "%s[%d]=%s" % (arr,i,val)
>>> pieces.append(bit)
>>> print " ".join(pieces)
And if I stepped even farther back, it's likely that I'd have
descriptive names for my lists, and consequently it'd look more like:
>>> pieces = ["%d" % (i,)]
>>> arrays = ["names", "dates", "faces"]
>>> for arr in arrays:
>>> arr = "arr%d" % x
>>> val = locals()[arr][i]
>>> bit = "%s[%d]=%s" % (arr,i,val)
>>> pieces.append(bit)
>>> print " ".join(pieces)
I usually prefer to have a collection of objects instead of a bunch of
synchronized lists, though, so it's even more likely that I'd be
writing a __str__ method on a class.
Again, best of luck -- sounds like the ASPN recipe has made you happy,
and I concede that it's cool -- Eval'ing anything always makes me
nervous, though :)
--G.
--
Geoff Gerrietts "People talk fundamentals and superlatives
<geoff at gerrietts net> and then make some changes of detail."
http://www.gerrietts.net --Oliver Wendell Holmes Jr
More information about the Python-list
mailing list