Question about output...

Erik Max Francis max at alcyone.com
Thu Oct 17 05:04:31 CEST 2002


Tony Warmath wrote:

>     I'm a C++ programmer and I'm trying to pick up on Python, so I've
> starting out making the same programs I have in college in C++ except
> coding
> them in Python, and I'm already stumped. I'm trying to produce the
> Python
> equivalent of this statement in C++:
> 
> cout << "The average of " << firstInt << " and " << secondInt << " is
> " <<
> average << endl;
> 
> using variables and strings in one line of output. I've seen some FAQs
> but
> didn't like the way they said do them, i.e. assigning a variable to
> the
> whole string. What's the Python equivalent to that statement to get me
> on my
> way. Thanx!

As other people have pointed out, something as simple as

    print "The average of", first, "and", second, "is", average

or

    print "The average of %d and %d is %d" % (first, second, average)

One of the primary motivations for iostreams in C++ vs. stdio is that
stdio (printf, etc.) does not support polymorphism, and that's the
motivation for having the << stream insertion operator (the reason for
it being an operator is so that it's easily chained together like you
used above).  In Python this motivation simply doesn't exist, since
printing an object automatically calls str on it (a function which
converts it to a string, and which can be overridden with __str__
methods), so right out of the gate Python's printing facilities do not
suffer from the limitations of stdio.

You could, of course, write your own iostream-like class wrapper so that
you can continue to use << as an insertion operator; it would in fact be
quite straightforward, even if one wanted to support manipulators:

... snip ...

import sys

class IOManipulator:

    def __init__(self, function=None):
        self.function = function

    def do(self, output):
        self.function(output)


class OStream:

    def __init__(self, output=None):
        if output is None:
            output = sys.stdout
        self.output = output

    def __lshift__(self, thing):
        if isinstance(thing, IOManipulator):
            thing.do(self.output)
        else:
            self.output.write(str(thing))
        return self


def main():
    endl = IOManipulator(lambda s: (s.write('\n'), s.flush()))
    cout = OStream()
    cout << "The average of " << 1 << " and " << 3 << " is " << (1 +
3)/2 << endl

if __name__ == '__main__': main()

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ Be able to be alone.  Lose not the advantage of solitude.
\__/ Sir Thomas Browne
    REALpolitik / http://www.realpolitik.com/
 Get your own customized newsfeed online in realtime ... for free!



More information about the Python-list mailing list