简体   繁体   中英

Extra line in output when printing inside a loop

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

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 (eg, by using rstrip() )

The best general answer to this problem is to strip the trailing newline (if any!) as soon as you read it:

f = open('tasks.txt')
for i, text in enumerate(f, start=1):
    text = text.rstrip('\n')
    if i >= 2 and i <= 4:
        print "(%d) %s" % (i, text)

That way you uncouple your output from your input ... your output code may be 20 lines away or in a different function/method or even in a different module. Compensating for a newline in input by using a comma at the end of the print statement is not a robust solution.

In order to not have a blank line, you need , at the end of the print statement

Example:

for i in range(10):
    print i,

>>>0 1 2 3 4 5 6 7 8 9

for i in range(10):
    print i

>>>
0
1
2
3
4
5
6
7
8
9

Iterating over files keeps the newlines from the file. So there's one newline from your print, and one from the string.

A good way to test file semantics is with StringIO . Take a look:

>>> from StringIO import StringIO
>>> x = StringIO("abc\ncde\n")
>>> for line in x: print repr(line)
... 
'abc\n'
'cde\n'

The comma suppresses the newline from the print, as Levon says, so that there's only the newline from the string.

I strip newlines from strings using s.rstrip('\\n') . It gets rid of any trailing newlines in any modernish format (Unix, Windows, or old Mac OS). So you can do print "(%d) %s" % (i, text.rstrip('\\n')) instead.

There is a very simple fix for this.

Let's say I have, for arguments sake, a .txt file (called numbers.txt) which I am reading from with the values:

234234
777776
768768

Then, using the following code:

filename = numbers.txt

with open(filename) as file_object:
    for line in file_object:
        print(line)

Would give you the extra blank line as you are having problems with. But with a small change, you can get rid of the extra blank lines using the rstrip() method. So the code becomes:

filename = numbers.txt

with open(filename) as file_object:
    for line in file_object:
        print(line.rstrip())

Now you will get your results without those annoying blank lines between them!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM