Translating a Perl script into Python

Sheila King sheila at spamcop.net
Sat Jan 20 18:22:01 EST 2001


[reply posted and e-mailed]

On 20 Jan 2001 23:47:16 +0100, Carel Fellinger <cfelling at iae.nl> wrote in
comp.lang.python in article <94d4hk$1sq$1 at animus.fel.iae.nl>:

:Sheila King <sheila at thinkspot.net> wrote:
:
:for this piece of code
:>   print PROC "$key = $ENV{$key}\n";
:you used
:> 	PROC.write(key + " = " + os.environ[key] + "\n")
:
:whereas I often prefer (the (to me atleast) more Pythonic)
:        PROC.write("%s = %s\n" % (key,os.environ[key])
:
:and yet in some circumstances even the more elaborate variant
:        PROC.write("%(key)s = %(value)s\n" % {key:key, val:os.environ[key]})
:
:The latter form comes very close to the Perl way of coding, and
:is espescially suited for format strings spanning several lines.

Hmm. Interesting. I've kind of been scared off by the % stuff. I didn't
understand it, or what it was doing, and never really saw it mentioned in the
docs, other than:
"You can use the 'C'-like way of doing things..."
But I don't really know C, so that put me off.

But looking at your code, I'd venture that it works like this?
%s is a substitute for something that will be revealed later,
when you write
("%s = %s\n" % (key,os.environ[key])

The %s in the string is taking the place for something that comes later, and
then at the end you list in parenthese the later stuff, behind a % sign.

Um, did you leave out a parenthese in the above statement?

--
Sheila King
http://www.thinkspot.net/sheila/
http://www.k12groups.org/




More information about the Python-list mailing list