I am reading input for my python program from stdin (I have assigned a file object to stdin). The number of lines of input is not known beforehand. Sometimes the program might get 1 line, 100 lines or even no lines at all.
import sys
sys.stdin = open ("Input.txt")
sys.stdout = open ("Output.txt", "w")
def main():
for line in sys.stdin:
print line
main()
This is the closest to my requirement. But this has a problem. If the input is
3
7 4
2 4 6
8 5 9 3
it prints
3
7 4
2 4 6
8 5 9 3
It prints an extra newline after every line. How do I fix this program or whats the best way to solve this problem?
EDIT: Here is the sample run http://ideone.com/8GD0W7
EDIT2: Thanks for the Answer. I got to know the mistake.
import sys
sys.stdin = open ("Input.txt")
sys.stdout = open ("Output.txt", "w")
def main():
for line in sys.stdin:
for data in line.split():
print data,
print ""
main()
Changed the program like this and it works as expected. :)
x you can add a comma (,) at the end of the print statement that will remove newline from print Python.
The new line character in Python is \n . It is used to indicate the end of a line of text. You can print strings without adding a new line with end = <character> , which <character> is the character that will be used to separate the lines.
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.
The readline method reads one line from the file and returns it as a string. The string returned by readline will contain the newline character at the end. This method returns the empty string when it reaches the end of the file.
the python print
statement adds a newline, but the original line already had a newline on it. You can suppress it by adding a comma at the end:
print line , #<--- trailing comma
For python3, (where print
becomes a function), this looks like:
print(line,end='') #rather than the default `print(line,end='\n')`.
Alternatively, you can strip the newline off the end of the line before you print it:
print line.rstrip('\n') # There are other options, e.g. line[:-1], ...
but I don't think that's nearly as pretty.
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