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
Mary-Kate OlsenOriginal
2024-12-01 02:10:12307browse

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))

Using %-Formatting with Dictionaries

Another option is to use a dictionary:

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

Using New-Style String Formatting

Python's newer string formatting offers multiple conveniences:

  • Using Numbers:

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

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

    print("Total score for " + str(name) + " is " + str(score))

Using print() Function with Parameters

This approach does not require any special formatting syntax:

print("Total score for", name, "is", score)

For better control over spacing, use the sep parameter:

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

Using f-Strings (Python 3.6 )

f-strings make this process highly concise:

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

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!

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