[Tutor] here's a printf() function
Sha vais
shavais at hotmail.com
Tue Mar 16 16:02:30 EST 2004
I'm a C / C++ programmer (in a weak kind of a way, I think) and I'm learning
Python (and loving it). I was slightly irritated by the automagical spaces
between elements and ending carriage return that Python's built in "print"
function does, so I made a printf() function that I thought I'd share.
(This list probably gets one of these every other week or so? Lol..)
Here's the module file, sf_utils.py ---
"""
Some basic formatted string output functions to make things easier
for someone who is used to C.
"""
from sys import stdout
def printf(format, *args):
"Write the arguments to standard out in the specified format."
s = format % args
stdout.write(s) # (no added spaces or ending carriage return, woohoo!)
def fprintf(file, format, *args):
"Write the arguments to the given open file in the specified format."
s = format % args
file.write(s)
def sprintf(format, *args):
"Return a string with the arguments concatenated in the specified
format."
s = format % args
return s
----
That's it, hehe. Ez as Py. Now I can do stuff like...
----
>>>from sf_utils import printf
>>>printf("%s! There's a %s fly in my %4.5fth bowl of %s!\n",
>>>"Argh","flipping", 3.14159236, "goo")
Argh! There's a flipping fly in my 3.14159th bowl of goo!
----
Kinda silly and pointless, I guess, but then, kinda maybe not.
~Shavais
p.s. I was in search of the py_compile.compile(filename,...) function
(which I gratefully found, whew) and I came across an old post by someone
who thought "is" was not behaving properly and thought it was a bug in the
interpreter. Remember that "is" is not a value comparison. If it were, how
would you see if the variable x is referring to the same memory space (the
same object) as the variable y? (While processing complex data structures,
for example.) That's what "is" does. If you use "is" interchangeably with
"==" you will make nasty bugs. Your program might behave one way in .py
form, and another in .pyc form, for example. (Or one way on Monday, and
another on Tuesday, for that matter, lol.) What they really mean by "object
identity" (to a C programmer like me) is "pointer equality." Every Python
variable is a pointer. '==' tests to see if the values at the memory
addresses that the pointers are pointing to are the same. 'is' tests to see
if the pointers are pointing to the same memory address. Two completely
different tests. Two different python variables, who's values are the same,
may refer to the same memory location, or they may not. If you use "is"
when you mean "==", don't blame the interpretter for producing strange
results, hehe.
_________________________________________________________________
Is your PC infected? Get a FREE online computer virus scan from McAfee®
Security. http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963
More information about the Tutor
mailing list