Home >Backend Development >Python Tutorial >How Can I Avoid Newlines and Spaces When Printing in Python?

How Can I Avoid Newlines and Spaces When Printing in Python?

DDD
DDDOriginal
2024-12-27 09:50:10305browse

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:

  1. Import Python 3's print function:
from __future__ import print_function

This allows the use of the Python 3 solution mentioned above.

  1. Use sys.stdout.write() (recommended for Python 2):
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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn