[Tutor] console output that is same in Python 2 and 3
mail at timgolden.me.uk
Tue Sep 28 10:56:14 CEST 2010
On 27/09/2010 17:11, Thierry Tung wrote:
> Hello tutor at python.org.
> How can I write strings to the console in a way that will give the same result in Python 3 and Python 2?
> I tried sys.stdout.write('hello') on Microsoft vista.
> with python 3.1.2
> with python 2.7
> Why is the string length appended to the output with python 3.1.2?
Because in Py 3.x the .write method returns the length written.
The interpreter echoes the non-None return value of any function
to stdout. This won't happen when you run the program -- you won't
get a stream of numbers. To avoid it happening in the interpreter,
simply assign the return value:
n = sys.stdout.write("hello")
In Python 2.x n will be None; in Python 3.x it will be 5
More information about the Tutor