How to Suppress Newlines and Spaces in Print Output
When using Python's print() function, newlines or spaces often separate the output arguments. This behavior can be frustrating when trying to achieve continuous output without breaks.
One solution for Python 3 is to utilize the sep= and end= parameters of the print() function. To eliminate newlines, set end='' to suppress the automatic newline added after each argument:
print('.', end='')
To prevent spaces between arguments, set sep='' to concatenate them without separation:
print('a', 'b', 'c', sep='')
Both parameters can be used simultaneously to customize the output format further. Additionally, the flush=True keyword can be used to force immediate output without buffering.
For Python 2.6 and 2.7, there are two options. One involves importing Python 3's print function using the future module, which enables the Python 3 solution above. However, note that flush is not supported in Python 2's imported print function.
Alternatively, you can use sys.stdout.write():
import sys sys.stdout.write('.') sys.stdout.flush() # May be necessary to force immediate output
The above is the detailed content of How Can I Control Spaces and Newlines in Python's Print Output?. For more information, please follow other related articles on the PHP Chinese website!