String interpolation is a technique used in various programming languages to embed expressions or variables within string literals. It allows you to construct strings by combining static text with dynamic content. The resulting string is formed by replacing placeholders or variables with their actual values.
Python offers several ways to perform string interpolation:
format()
method when you need more flexibility or using Python older than 3.6.Each method has its own advantages and disadvantages.
f
or F
as prefix and curly braces {}
to indicate placeholders and embed expressions directly inside the string.name = "John"
age = 30
message = f"My name is {name} and I am {age} years old."
print(message)
# My name is John and I am 30 years old.
area = 5 * 7
print(f"The area of the rectangle is {area} square meters.")
# The area of the rectangle is 35 square meters.
There are many different format specifiers, written after a colon (:
) inside the curly braces that enclose the expression, that can be used with f-strings. They can be used to specify the type, precision, alignment, padding, grouping, and other aspects of the formatting.
name = "Alice"
age = 25
print(f"Hello, {name}. You are {age:03d} years old.")
# Hello, Alice. You are 025 years old.
format()
method, a versatile option available in all Python versions. It allows you to define placeholders in the string using curly braces and pass the values as arguments to the format()
method.name = "John"
age = 30
message = "My name is {} and I am {} years old."
print(message.format(name, age))
# My name is John and I am 30 years old.
area = 5 * 7
print("The area of the rectangle is {0} square meters.".format(area))
# The area of the rectangle is 35 square meters.
format()
method. It uses placeholders with a %
symbol and format specifiers like s
(string), d
(integer), and f
(float) to define the type of value to be inserted.name = "John"
age = 30
message = "My name is %s and I am %d years old." % (name, age)
print(message)
# My name is John and I am 30 years old.
area = 5 * 7
print("The area of the rectangle is %.2f square meters." % (area))
# The area of the rectangle is 35.00 square meters.
$
to indicate placeholders and the substitute()
method to pass the values.from string import Template
name = "David"
age = 40
t = Template("Hello, $name. You are $age years old.")
print(t.substitute(name=name, age=age))
# Output: Hello, David. You are 40 years old.