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

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

Mary-Kate Olsen
Release: 2024-12-02 20:50:11
Original
113 people have browsed it

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

Printing Multiple Elements on the Same Line

Your code attempts to print "Total score for %s is %s Alice 100", which differs from your expected output due to incorrect formatting. To rectify this, use one of the following methods:

1. Use a Tuple with %-Formatting:

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

2. Use a Dictionary with %-Formatting:

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

3. Use New-Style String Formatting (Python 3):

print("Total score for {} is {}".format(name, score))
Copy after login

4. Concatenate Strings:

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

5. Use Function Parameters (Python 3):

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

6. Use F-String Formatting (Python 3.6 ):

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

It is recommended to use either method 5 or 6 for clarity and ease of use.

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