Appending Strings to Standard Output: Printing Without Newlines or Spaces
In Python, the print function often adds newlines or spaces between output values. However, there are ways to prevent this and "append" strings to the standard output stream.
Python 3
The print function in Python 3 offers the sep and end parameters:
For example:
print('.', end='') # No newline added print('a', 'b', 'c', sep='') # No spaces added
Python 2.6 and 2.7
In Python 2.6 and 2.7, the print function from Python 3 can be imported using __future__:
from __future__ import print_function
This allows the use of the sep and end parameters as in Python 3. However, the flush keyword is not available in Python 2, so manual flushing with sys.stdout.flush() is necessary.
Alternately, sys.stdout.write() can be used in conjunction with sys.stdout.flush():
import sys sys.stdout.write('.') sys.stdout.flush()
The above is the detailed content of How Can I Append Strings to Standard Output in Python Without Newlines or Spaces?. For more information, please follow other related articles on the PHP Chinese website!