Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid new line in readline() function in python 3x? [duplicate]

I am a new to python programming. I've followed the "Learn python the hard way" book but that is based on python 2x.

def print_one_line(line_number,f):
    print(line_number,f.readline())

In this function every time it prints A line and a new line.

1 gdfgty

2 yrty

3 l

I read the documentary that if i put a , (comma) after readline() then it won't print a new \n. Here is the documentary:

Why are there empty lines between the lines in the file? The readline() function returns the \n that's in the file at the end of that line. This means that print's \n is being added to the one already returned by readline() fuction. To change this behavior simply add a , (comma) at the end of print so that it doesn't print its own .

When I run the file with python 2x then it is OK, but when I do it in python 3x then the newline is printed. How to avoid that newline in python 3x?

like image 388
Mastan Avatar asked Jul 29 '15 20:07

Mastan


Video Answer


3 Answers

Since your content already contains the newlines you want, tell the print() function not to add any by using the optional end argument:

def print_one_line(line_number,f):
    print(line_number,f.readline(), end='')
like image 66
TigerhawkT3 Avatar answered Oct 13 '22 05:10

TigerhawkT3


Beside the other ways, you could also use:

import sys
sys.stdout.write(f.readline())

Works with every Python version to date.

like image 41
bufh Avatar answered Oct 13 '22 05:10

bufh


Rather than skipping the newline on output, you can strip it from the input:

print(line_number, f.readline().rstrip('\n'))
like image 1
Mark Ransom Avatar answered Oct 13 '22 03:10

Mark Ransom