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
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.
To print on the same line in Python, add a second argument, end=' ', to the print() function call.
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.
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.
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()
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With