Python Forum

Full Version: print not printing newlines
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I've got 2.7 and 3.3 versions. The 3.3 is in spyder on windows. The 2.7 is python in linux.

I'm reading data from a socket, and If I do this,

print "received data:", data

It outputs correctly, with the newlines in the data causing output on separate lines, as desired.

But this won't work in 3.3 and so, I've done this,

print("received data:",data)

and then it spits out all the text and replaces the newlines with \n instead and doesn't actually do the newlines.

How can I do this compatibly between the 2 versions?
Convert to string before printing
I tried this: print('Received',data.decode('utf-8') )

This works on 3.3 but not on 2.7.


In Python, is there a way to do something like this, which I could do in C code:
#ifdef version 3.3
doit this way
#else
that way
#endif

So, is there a way, other than supplying two sets of code to do this?
(Jul-03-2021, 04:46 PM)rocket777 Wrote: [ -> ]In Python, is there a way to do something like this, which I could do in C code:
#ifdef version 3.3
doit this way
Yes that is a smart idea. You can do:
import sys
if sys.version.startswith("3.3"):
    do_something()
You can also tell python2 to run the code as if it's python3.

from __future__ import print_function

data = b'foobar'
print('Received', data.decode('utf-8'))