383

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

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
user1985351
  • 4,589
  • 6
  • 22
  • 25
  • 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. – Karl Knechtel Mar 29 '23 at 05:35

13 Answers13

677

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}')
    
Blender
  • 289,723
  • 53
  • 439
  • 496
  • 8
    of course, there's always the age-old disapproved method: `print("Total score for "+str(name)"+ is "+str(score))` – Snakes and Coffee Mar 08 '13 at 04:46
  • 6
    @SnakesandCoffee: I'd just do `print("Total score for", name, "is", score)` – Blender Mar 08 '13 at 04:47
  • 4
    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'`. – pepr Mar 08 '13 at 13:15
  • 8
    FYI, as of Python 3.6, we get [f-strings](https://www.python.org/dev/peps/pep-0498/), 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). – ShadowRanger Dec 07 '16 at 01:41
  • @SnakesandCoffee Why is `print("Total score for "+str(name)"+ is "+str(score))` disapproved? – theQuestionMan Nov 04 '20 at 00:42
  • @SnakesandCoffee Lol...got the answer...some other guy also had the same question...https://stackoverflow.com/questions/41008941/why-is-printtext-strvar1-more-text-strvar2-described-as-disappr – theQuestionMan Nov 04 '20 at 00:47
  • Is there one that is common for Python 2 and Python 3 ? – Joe Race Apr 10 '22 at 11:52
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}')
Vikas Gupta
  • 10,779
  • 4
  • 35
  • 42
53

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}') 
Gavriel Cohen
  • 4,355
  • 34
  • 39
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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Abhishek
  • 471
  • 5
  • 17
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))
Paolo Rovelli
  • 9,396
  • 2
  • 58
  • 37
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.

Wolf
  • 9,679
  • 7
  • 62
  • 108
TheExorcist
  • 1,966
  • 1
  • 19
  • 25
  • 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... – Wolf May 19 '21 at 14:42
12

Just try:

print("Total score for", name, "is", score)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
sarora
  • 512
  • 1
  • 6
  • 11
7

Use f-string:

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

Or

Use .format:

print("Total score for {} is {}".format(name, score))
Innat
  • 16,113
  • 6
  • 53
  • 101
6
print("Total score for %s is %s  " % (name, score))

%s can be replace by %d or %f

strickt01
  • 3,959
  • 1
  • 17
  • 32
user6014455
  • 61
  • 1
  • 1
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

Supercolbat
  • 311
  • 2
  • 8
  • 18
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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
3

The easiest way is as follows

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

Just put an "f" in front.

Joe Race
  • 178
  • 10
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>