How to insert .format multiple variables in Python

How to insert .format multiple variables in Python

format() is a built-in function that can insert a value or more into a string's placeholder. This tutorial will help us learn to insert multiple variables with format().

Syntax

# Empty placeholders
"{} {}".format(value1, value2)

# Indexed
"{0} {1}".format(value1, value2)

# Named
"{val1} {val2}".format(val1=value1, val2=value2)

 

Multiple variables with the format() with examples

In the following example, we'll see how to insert multiple variables with empty, indexed, and named placeholders.

Empty placeholders

mystr = "Hello, my name is {}. I'm {} years old.".format("Pytutorial", 3)

# Print
print(mystr)

Output:

Hello, my name is Pytutorial. I'm 3 years old.

As you can see, we have set placeholders depending on the format parameters.

named placeholders

mystr = "Hello, my name is {name}. I'm {age} years old.".format(name="Pytutorial", age=3)

# Print
print(mystr)

Output:

Hello, my name is Pytutorial. I'm 3 years old.

Indexed placeholders

mystr = "Hello, my name is {1}. I'm {0} years old.".format(3, "Pytutorial")

# Print
print(mystr)

Output:

Hello, my name is Pytutorial. I'm 3 years old.