Home >Backend Development >Python Tutorial >How Can I Print Multiple Items on the Same Line in Python?

How Can I Print Multiple Items on the Same Line in Python?

Barbara Streisand
Barbara StreisandOriginal
2024-12-11 06:34:10157browse

How Can I Print Multiple Items on the Same Line in Python?

Printing Multiple Items on the Same Line

When executing scripts, it's often desirable to display output in a specific format. A common requirement is to print multiple items on the same line, one at a time.

Current Approach and Issue

Currently, the script produces output in two separate lines:

Installing XXX...
[DONE]

The goal is to print both "Installing XXX..." and "[DONE]" on the same line.

Solution

There are different approaches to printing multiple items on the same line, depending on the language used. The solutions below cover Python 2 and Python 3:

Python 3:

def install_xxx():
    print("Installing XXX...      ", end="", flush=True)

install_xxx()
print("[DONE]")

The print() function allows specifying an end parameter. Setting it to an empty string prevents it from issuing a trailing newline. flush=True is added to ensure the output is immediately displayed.

Python 2:

def install_xxx():
   print "Installing XXX...      ",

install_xxx()
print "[DONE]"

In Python 2, adding a comma to the end of the print() statement also prevents it from emitting a new line, though it will leave an extra space in the output.

The above is the detailed content of How Can I Print Multiple Items on the Same Line 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