Printing Without Newlines or Spaces
When using print in Python with multiple arguments, a newline or space is automatically inserted between each value. This can make it difficult to print output as a single, continuous string.
Python 3
To suppress the newline or space, use the sep and end parameters. To remove the newline, set end to an empty string:
print('.', end='')
To remove the space between arguments, set sep to an empty string:
print('a', 'b', 'c', sep='')
Python 2.6 and 2.7
Method 1: Using the Future Module
Import the print function from Python 3 using the future module:
from __future__ import print_function
This allows you to use the same sep and end parameters as in Python 3.
Method 2: Using sys.stdout.write
Alternatively, you can use sys.stdout.write to append to the standard output stream:
import sys sys.stdout.write('.')
To ensure immediate output, flush stdout manually:
sys.stdout.flush()
By using these techniques, you can seamlessly append strings to the standard output stream, without introducing newlines or spaces.
The above is the detailed content of How Can I Print Strings in Python Without Newlines or Spaces?. For more information, please follow other related articles on the PHP Chinese website!