Python Forum
print not printing newlines - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: print not printing newlines (/thread-34166.html)



print not printing newlines - rocket777 - Jul-02-2021

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?


RE: print not printing newlines - deanhystad - Jul-03-2021

Convert to string before printing


RE: print not printing newlines - rocket777 - Jul-03-2021

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?


RE: print not printing newlines - ibreeden - Jul-03-2021

(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()



RE: print not printing newlines - bowlofred - Jul-03-2021

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'))