[python] Print multiple arguments in Python

This is just a snippet of my code:

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

But I want it to print out:

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

where name is a variable in a list and score is an integer. This is Python 3.3 if that helps at all.

This question is related to python printing python-3.x arguments

The answer is


Use: .format():

print("Total score for {0} is {1}".format(name, score))

Or:

// Recommended, more readable code

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

Or:

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

Or:

`print("Total score for %s is %d" % (name, score))`

In Python 3.6, f-string is much cleaner.

In earlier version:

print("Total score for %s is %s. " % (name, score))

In Python 3.6:

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

will do.

It is more efficient and elegant.


There are many ways to print that.

Let's have a look with another example.

a = 10
b = 20
c = a + b

#Normal string concatenation
print("sum of", a , "and" , b , "is" , c) 

#convert variable into str
print("sum of " + str(a) + " and " + str(b) + " is " + str(c)) 

# if you want to print in tuple way
print("Sum of %s and %s is %s: " %(a,b,c))  

#New style string formatting
print("sum of {} and {} is {}".format(a,b,c)) 

#in case you want to use repr()
print("sum of " + repr(a) + " and " + repr(b) + " is " + repr(c))

EDIT :

#New f-string formatting from Python 3.6:
print(f'Sum of {a} and {b} is {c}')

Keeping it simple, I personally like string concatenation:

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

It works with both Python 2.7 an 3.X.

NOTE: If score is an int, then, you should convert it to str:

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

Just try:

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

This was probably a casting issue. Casting syntax happens when you try to combine two different types of variables. Since we cannot convert a string to an integer or float always, we have to convert our integers into a string. This is how you do it.: str(x). To convert to a integer, it's: int(x), and a float is float(x). Our code will be:

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

Also! Run this snippet to see a table of how to convert different types of variables!

_x000D_
_x000D_
<table style="border-collapse: collapse; width: 100%;background-color:maroon; color: #00b2b2;">
<tbody>
<tr>
<td style="width: 50%;font-family: serif; padding: 3px;">Booleans</td>
<td style="width: 50%;font-family: serif; padding: 3px;"><code>bool()</code></td>
  </tr>
 <tr>
<td style="width: 50%;font-family: serif;padding: 3px">Dictionaries</td>
<td style="width: 50%;font-family: serif;padding: 3px"><code>dict()</code></td>
</tr>
<tr>
<td style="width: 50%;font-family: serif;padding: 3px">Floats</td>
<td style="width: 50%;font-family: serif;padding: 3px"><code>float()</code></td>
</tr>
<tr>
<td style="width: 50%;font-family: serif;padding:3px">Integers</td>
<td style="width: 50%;font-family: serif;padding:3px;"><code>int()</code></td>
</tr>
<tr>
<td style="width: 50%;font-family: serif;padding: 3px">Lists</td>
<td style="width: 50%font-family: serif;padding: 3px;"><code>list()</code></td>
</tr>
</tbody>
</table>
_x000D_
_x000D_
_x000D_


If score is a number, then

print("Total score for %s is %d" % (name, score))

If score is a string, then

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

If score is a number, then it's %d, if it's a string, then it's %s, if score is a float, then it's %f


There are many ways to do this. To fix your current code using %-formatting, you need to pass in a tuple:

  1. Pass it as a tuple:

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

A tuple with a single element looks like ('this',).

Here are some other common ways of doing it:

  1. Pass it as a dictionary:

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

There's also new-style string formatting, which might be a little easier to read:

  1. Use new-style string formatting:

    print("Total score for {} is {}".format(name, score))
    
  2. Use new-style string formatting with numbers (useful for reordering or printing the same one multiple times):

    print("Total score for {0} is {1}".format(name, score))
    
  3. Use new-style string formatting with explicit names:

    print("Total score for {n} is {s}".format(n=name, s=score))
    
  4. Concatenate strings:

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

The clearest two, in my opinion:

  1. Just pass the values as parameters:

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

    If you don't want spaces to be inserted automatically by print in the above example, change the sep parameter:

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

    If you're using Python 2, won't be able to use the last two because print isn't a function in Python 2. You can, however, import this behavior from __future__:

    from __future__ import print_function
    
  2. Use the new f-string formatting in Python 3.6:

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

Use f-string:

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

Or

Use .format:

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

This is what I do:

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

Remember to put a space after for and before and after is.


Just follow this

idiot_type = "the biggest idiot"
year = 22
print("I have been {} for {} years ".format(idiot_type, years))

OR

idiot_type = "the biggest idiot"
year = 22
print("I have been %s for %s years."% (idiot_type, year))

And forget all others, else the brain won't be able to map all the formats.


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

%s can be replace by %d or %f


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to printing

How do I print colored output with Python 3? Print a div content using Jquery Python 3 print without parenthesis How to find integer array size in java Differences Between vbLf, vbCrLf & vbCr Constants Printing variables in Python 3.4 Show DataFrame as table in iPython Notebook Removing display of row names from data frame Javascript window.print() in chrome, closing new window or tab instead of cancelling print leaves javascript blocked in parent window Print a div using javascript in angularJS single page application

Examples related to python-3.x

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation Replace specific text with a redacted version using Python Upgrade to python 3.8 using conda "Permission Denied" trying to run Python on Windows 10 Python: 'ModuleNotFoundError' when trying to import module from imported package What is the meaning of "Failed building wheel for X" in pip install? How to downgrade python from 3.7 to 3.6 I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."? Iterating over arrays in Python 3 How to upgrade Python version to 3.7?

Examples related to arguments

docker build with --build-arg with multiple arguments ARG or ENV, which one to use in this case? How to have multiple conditions for one if statement in python Gradle task - pass arguments to Java application Angularjs - Pass argument to directive TypeError: method() takes 1 positional argument but 2 were given Best way to check function arguments? "Actual or formal argument lists differs in length" Python: Passing variables between functions Print multiple arguments in Python