String interpolation question
Michael Hudson
mwh at python.net
Tue Apr 16 06:01:43 EDT 2002
Fernando PĂ©rez <fperez528 at yahoo.com> writes:
> 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";
When I found myself doing this, I wrote something like this:
import re
template = """\
def copy_array(self, arr1, arr2):
{{ arr1[!] = arr2[!]; }}
"""
prog = re.compile("\\{\\{.*?\\}\\}")
def expand_template(template, n):
def replacer(match):
s = match.group(0)[2:-2]
r = []
for i in range(n):
r.append(s.replace('!', `i`))
return ''.join(r)
return prog.sub(replacer, template)
then:
>>> print expand_template(template, 3)
def copy_array(self, arr1, arr2):
arr1[0] = arr2[0]; arr1[1] = arr2[1]; arr1[2] = arr2[2];
>>>
I say "something like" because my code was a bit less trivial, came
before nested scopes, and I can't quite remember the markup I used.
Ah yes, more here:
http://groups.google.com/groups?selm=m31ziyfy28.fsf_-_%40atrus.jesus.cam.ac.uk
> To me, the above line is clear, unambiguous and requires zero contortions to
> either write or read (by the coder).
To me it looks scarily long...
HTH,
M.
--
incidentally, asking why things are "left out of the language" is
a good sign that the asker is fairly clueless.
-- Erik Naggum, comp.lang.lisp
More information about the Python-list
mailing list