While working on a programming problem today, I noticed that Python's print output defaults to line feed output and has spaces after the output.
The title requires an output
122
And my output is:
1
2
2
So I checked in Baidu and found a way to cancel the automatic line breaks in print: it's to put a comma after the value of print, e.g., print x,
Sure enough, no more line breaks, but the output is still incorrect, requiring an output of 122, while my output is 1 2 2
So I continued to Baidu to check the method, and found that the print method of Python2 and Python3 are different. the print of Python2 can output directly without adding (), for example, print 'hello world', while Python3 needs to add brackets print("hello world"), and the print method of Python3 has parameters. print method has parameters, for example, sep means the concatenation between strings, and end means what to end with. If no parameter is set default sep=' ', end='\n', so I changed my code to:
print (i,end=''), but I found that it compiles wrongly because I am using Python2, and running Python2's print is without arguments, and similarly, if I use print x, which is a comma form, in Python3, it compiles wrongly.
So I didn't know what to do, and continued to Baidu to find out:
from __future__ import print_function
Just add this to the front of the program and you can use the parameter in Python2. Finally it outputs 122 correctly
Later, I found another way to do this is to use
()
I changed the code to:
(str(i))
It also correctly outputs 122
Above this to solve the problem of Python print output without line breaks and no spaces is all I have to share with you, I hope to be able to give you a reference, and I hope you will support me more.