Home >Backend Development >Python Tutorial >How Can I Avoid Newlines and Spaces When Printing in Python?
Avoiding Newlines and Spaces in Output Strings
When using the print function in Python, it often adds a newline or space between the output values. To prevent this and achieve uninterrupted printing, consider using the sep and end parameters.
Python 3
In Python 3, specify end='' to eliminate newlines:
print('.', end='')
To remove spaces between arguments, use sep='':
print('a', 'b', 'c', sep='')
To control both parameters simultaneously:
print('.', end='', sep='')
Python 2.6 and 2.7
For Python 2.6 and 2.7, you have two options:
from __future__ import print_function
This allows the use of the Python 3 solution mentioned above.
import sys sys.stdout.write('.') sys.stdout.flush()
This writes directly to the standard output stream, ensuring immediate printing. However, you may need to call sys.stdout.flush() to guarantee immediate output.
The above is the detailed content of How Can I Avoid Newlines and Spaces When Printing in Python?. For more information, please follow other related articles on the PHP Chinese website!