How can I print multiple things (fixed text and/or variable values) on the same line, all at once?
Asked Answered
D

14

387

I have some code like:

score = 100
name = 'Alice'
print('Total score for %s is %s', name, score)

I want it to print out Total score for Alice is 100, but instead I get Total score for %s is %s Alice 100. How can I get everything to print in the right order with the right formatting?


See also: How can I print multiple things on the same line, one at a time? ; How do I put a variable’s value inside a string (interpolate it into the string)?

Deedeeann answered 8/3, 2013 at 3:51 Comment(1)
OP of this question originally clearly had a string-formatting approach in mind, which would make the question a) a duplicate and b) caused by a typo (clearly the intent is to use %-style formatting, but the actual % operator is not used as required). However, the question received a truly excellent top answer that comprehensively shows approaches to the problem, so I ended up selecting this question as a canonical and editing the question title to reflect the breadth that was assumed in the answer.Dagoba
T
686

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}')
    
Teflon answered 8/3, 2013 at 3:52 Comment(7)
of course, there's always the age-old disapproved method: print("Total score for "+str(name)"+ is "+str(score))Tribunal
@SnakesandCoffee: I'd just do print("Total score for", name, "is", score)Teflon
My +1. These days I prefer the .format() as more readable than the older % (tuple) -- even though I have seen tests that show the % interpolation is faster. The print('xxx', a, 'yyy', b) is also fine for simple cases. I recommend also to learn .format_map() with dictionary as the argument, and with 'ssss {key1} xxx {key2}' -- nice for generating texts from templates. There is also the older string_template % dictionary. But the templates do not look that clean: 'ssss %(key1)s xxx %(key2)s'.Pelvic
FYI, as of Python 3.6, we get f-strings, so you can now also do print(f"Total score for {name} is {score}") with no explicit function calls (as long as name and score are in scope obviously).Rae
@SnakesandCoffee Why is print("Total score for "+str(name)"+ is "+str(score)) disapproved?Sickening
@SnakesandCoffee Lol...got the answer...some other guy also had the same question...#41009441Sickening
Is there one that is common for Python 2 and Python 3 ?Luca
S
64

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}')
Sanguineous answered 11/8, 2016 at 13:7 Comment(2)
The first comment (#Normal string concatenation) is at least misleading.Draughtsman
Agree @Wolf. sep=" " is the default concatenation, but "normal concatenation" I think would be using print(,sep="").Karlakarlan
B
54

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

Or: f-string formatting from Python 3.6:

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

Can use repr and automatically the '' is added:

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

# or for advanced: 
print(f'Total score for {name!r} is {score!r}') 
Boastful answered 18/1, 2018 at 11:23 Comment(0)
S
23

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.

Sapheaded answered 23/5, 2017 at 10:9 Comment(0)
I
15

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))
Intentional answered 1/4, 2015 at 20:57 Comment(0)
O
15

Just follow this

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

OR

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

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

Ottilie answered 22/9, 2017 at 7:11 Comment(1)
I know this is quite old. But what about the new f"I have been {a} for {b} years"? I'm going by only that one recently...Draughtsman
L
12

Just try:

print("Total score for", name, "is", score)
Laroy answered 30/7, 2014 at 5:0 Comment(0)
D
7

Use f-string:

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

Or

Use .format:

print("Total score for {} is {}".format(name, score))
Degraw answered 7/7, 2018 at 6:8 Comment(2)
When exactly should .format be used, now that you have f-strings?Draughtsman
BTW: when are you using " and when ' quotation?Draughtsman
C
6
print("Total score for %s is %s  " % (name, score))

%s can be replace by %d or %f

Cloris answered 3/3, 2016 at 16:51 Comment(0)
K
5

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

Kopans answered 11/7, 2016 at 19:53 Comment(0)
L
5

The easiest way is as follows

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

Just put an "f" in front.

Luca answered 14/2, 2022 at 16:35 Comment(0)
S
3

This is what I do:

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

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

Snowdrop answered 21/12, 2015 at 9:51 Comment(0)
F
0

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!

<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>
Fault answered 1/1, 2021 at 21:57 Comment(0)
R
0
print(f"Total score calculation complete, {name=}, {score=}")
# this will print:
# Total score calculation complete, name='Alice', score=100

Note that this prints name='Alice', not just 'Alice'!

All features:

  • You get variable name printing along with variable value. This is extremely useful for debug printing. If you don't need it for a certain variable, omit the = sign.
  • If you rename, remove or add any debugged variables, this print line will remain correct
  • Don't worry about alignment. If you have multiple variables, is the 4-th argument score or age? Well, you don't care, it's correct regardless.
  • Note that this is only available for Python 3.8+
Reareace answered 17/11, 2023 at 15:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.