[Python-Dev] Pascaloid print substitute (Replacement for print in Python 3.0)
Greg Ewing
greg.ewing at canterbury.ac.nz
Mon Sep 5 03:53:01 CEST 2005
Here's a non-statement print substitute that provides
space insertion and newline suppression, and as a bonus
it allows Pascal-style numeric formatting.
Usage examples:
Print["The answer is", 42]
Print["Tons of spam:", n:6]
Print[x:5:2, "squared is", x*x:10:4]
Print["One", "Two", ...]
Print["Buckle my shoe"]
#----------------------------------------------------
import sys
class PasFormat(object):
def __init__(self, f):
self.f = f
def __getitem__(self, arg):
#print "PasFormat.__getitem__:", arg
if isinstance(arg, tuple):
space = ""
for item in arg:
self.f.write(space)
if item is Ellipsis:
break
self._do(item)
space = " "
else:
self.f.write("\n")
else:
self._do(arg)
self.f.write("\n")
def _do(self, item):
if isinstance(item, slice):
value = item.start
width = item.stop or 0
decimals = item.step
else:
value = item
width = 0
decimals = None
if decimals is not None:
chars = "%*.*f" % (width, decimals, value)
else:
chars = "%*s" % (width, value)
self.f.write(chars)
Print = PasFormat(sys.stdout)
if __name__ == "__main__":
n = 666
x = 3.1415
Print["The answer is", 42]
Print["Tons of spam:", n:6]
Print[x:5:2, "squared is", x*x:10:4]
Print["One", "Two", ...]
Print["Buckle my shoe"]
#----------------------------------------------------
--
Greg Ewing, Computer Science Dept, +--------------------------------------+
University of Canterbury, | A citizen of NewZealandCorp, a |
Christchurch, New Zealand | wholly-owned subsidiary of USA Inc. |
greg.ewing at canterbury.ac.nz +--------------------------------------+
More information about the Python-Dev
mailing list