Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
print not printing newlines
#1
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?
Larz60+ write Jul-03-2021, 11:51 AM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Fixed this time
Reply
#2
Convert to string before printing
Reply
#3
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?
Reply
#4
(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()
Reply
#5
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'))
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  printing a list contents without brackets in a print statement paracelx 1 2,081 Feb-15-2020, 02:15 AM
Last Post: Larz60+
  Printing output without print usage susmith552 1 1,625 Feb-07-2020, 07:52 PM
Last Post: Clunk_Head
  strip off just newlines Skaperen 11 5,225 Jun-19-2019, 06:28 PM
Last Post: Skaperen
  Print Not Printing Correctly kittylexi 3 3,258 Sep-11-2018, 04:38 AM
Last Post: Larz60+
  Search & Replace - Newlines Added After Replace dj99 3 3,356 Jul-22-2018, 01:42 PM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020