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