How do I insert multiple variables with string formatting?



How do I insert multiple variables with string formatting?


So long as your number of %s placeholders matches the number of variables you are providing after the %, it will insert them in the order in which you provide them. Take a look over the code below for a better understanding:

var1 = “awesome”
var2 = “ever”
print “Codecademy has the most %s coding lessons %s!” % (var1, var2)
# displays: “Codecademy has the most awesome coding lessons ever!”

If you don’t have the same number of placeholders as variables provided to it, you will get an error message like these:
TypeError: not all arguments converted during string formatting
TypeError: not enough arguments for format string
The first means you have more variables than placeholders, and the second means you have more placeholders than variables provided. This is a very common issue, so be on the lookout!

FAQ: Learn Python – Strings & Console Output – String Formatting with %, Part 1

2 posts were split to a new topic: Why Are There No Backslashes Here?


How would this be written for Python 3


The modulo format is still valid in Python 3. You may be interested to learn how str.format() works.

"The {} in {} falls mainly in the {}".format('rain', 'Spain', 'plains')

This page compares both methods…


Something to notice about the str.format() method …

def spam():
    return 'am'

print('S{0}-{1}-{0}'.format(spam(), 'I'))

What will the output be? Execute the code to find out.

How may times did the spam() function get called?