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
Release: 2024-12-11 06:34:10
Original
208 people have browsed it

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]
Copy after login

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]")
Copy after login

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]"
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template