Home >Backend Development >Python Tutorial >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))
2. Use a Dictionary with %-Formatting:
print("Total score for %(n)s is %(s)s" % {'n': name, 's': score})
3. Use New-Style String Formatting (Python 3):
print("Total score for {} is {}".format(name, score))
4. Concatenate Strings:
print("Total score for " + str(name) + " is " + str(score))
5. Use Function Parameters (Python 3):
print("Total score for", name, "is", score)
6. Use F-String Formatting (Python 3.6 ):
print(f'Total score for {name} is {score}')
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!