Monday, November 10, 2014

Handling automatic newlines in Python

While solving programming contest problems using Python, I came across an issue with the default 'print' function of Python. It adds a newline right after every time it is executed. Example:
Code:
print "Case 1#: "
print "Result"

Output:
Case 1#:
Result
As you can see, this usually has to be done like
Case 1#: Result
Now how do we do this in Python?
Solution:
For Python 2.7:
import sys
sys.stdout.write("Case 1#: ")
sys.stdout.write("Resutl\n")
For Python 3:
print("Case 1#: ", end="")
print("Result")

* Written by- Tafhim Ul Islam

No comments:

Post a Comment