Home > Backend Development > Python Tutorial > How to Print Multiple Elements on a Single Line in Python?

How to Print Multiple Elements on a Single Line in Python?

Mary-Kate Olsen
Release: 2024-12-01 02:10:12
Original
300 people have browsed it

How to Print Multiple Elements on a Single Line in Python?

Printing Multiple Elements on a Single Line

To print multiple elements on the same line, all at once, there are several approaches:

Using %-Formatting with Tuples

The original code you provided can be corrected using %-formatting by passing the placeholders as a tuple:

print("Total score for %s is %s" % (name, score))
Copy after login

Using %-Formatting with Dictionaries

Another option is to use a dictionary:

print("Total score for %(n)s is %(s)s" % {'n': name, 's': score})
Copy after login

Using New-Style String Formatting

Python's newer string formatting offers multiple conveniences:

  • Using Numbers:

    print("Total score for {} is {}".format(name, score))
    Copy after login
  • Using Explicit Names:

    print("Total score for {n} is {s}".format(n=name, s=score))
    Copy after login
  • Concatenating Strings:

    print("Total score for " + str(name) + " is " + str(score))
    Copy after login

Using print() Function with Parameters

This approach does not require any special formatting syntax:

print("Total score for", name, "is", score)
Copy after login

For better control over spacing, use the sep parameter:

print("Total score for ", name, " is ", score, sep='')
Copy after login

Using f-Strings (Python 3.6 )

f-strings make this process highly concise:

print(f'Total score for {name} is {score}')
Copy after login

The above is the detailed content of How to Print Multiple Elements on a Single 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