Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extra line in output when printing inside a loop

Tags:

python

I can't figure out why the code #1 returns an extra empty line while code #2 doesn't. Could somebody explain this? The difference is an extra comma at the end of the code #2.

# Code #1
file = open('tasks.txt')

for i, text in enumerate(filer, start=1):
    if i >= 2 and i <= 4:
        print "(%d) %s" % (i, text)

# Code #2
file = open('tasks.txt')

for i, text in enumerate(filer, start=1):
    if i >= 2 and i <= 4:
        print "(%d) %s" % (i, text),

Here is the content of my tasks.txt file:

line 1
line 2
line 3
line 4
line 5

Result from code #1:

(2) line 2

(3) line 3

(4) line 4

Result from code #2 (desired result):

(2) line 2
(3) line 3
(4) line 4
like image 455
finspin Avatar asked May 04 '12 21:05

finspin


People also ask

Why is Python printing an extra line?

By default, print statements add a new line character "behind the scenes" at the end of the string. This occurs because, according to the Python Documentation: The default value of the end parameter of the built-in print function is \n , so a new line character is appended to the string.

How do you print a loop on the same line in Python?

To print on the same line in Python, add a second argument, end=' ', to the print() function call.

How do you print multiple lines on the same line?

To print multiple expressions to the same line, you can end the print statement in Python 2 with a comma ( , ). You can set the end argument to a whitespace character string to print to the same line in Python 3. With Python 3, you do have the added flexibility of changing the end argument to print on the same line.

How do you print a space in a for loop in Python?

We add space in string in python by using rjust(), ljust(), center() method. To add space between variables in python we can use print() and list the variables separate them by using a comma or by using the format() function.


1 Answers

The trailing , in the print statement will surpress a line feed. Your first print statement doesn't have one, your second one does.

The input you read still contains the \n which causes the extra linefeed. One way to compensate for it is to prevent print from issuing a linefeed of its own by using the trailing comma. Alternatively, and arguably a better approach, you could strip the newline in the input when you read it (e.g., by using rstrip() )

like image 76
Levon Avatar answered Sep 23 '22 15:09

Levon