Skip to content
DeveloperMemos

String Interpolation in Python

Python, String Interpolation, Programming1 min read

String interpolation is a powerful feature in Python that allows you to embed expressions or variables within string literals. It provides an elegant way to construct complex strings without having to manually concatenate different parts. In this article, we will delve into the world of string interpolation in Python and demonstrate its usage with various examples.

Basic String Interpolation

Python offers multiple ways to perform string interpolation. One of the most common methods is using the % operator. Let's take a look at a basic example:

1name = "Alice"
2age = 25
3message = "My name is %s and I am %d years old." % (name, age)
4print(message)

In this example, the %s and %d placeholders are used to denote where the values of name and age should be inserted, respectively. The values are provided after the % operator within parentheses.

The output of this code snippet will be:

1My name is Alice and I am 25 years old.

Formatting Specifiers

Formatting specifiers allow you to control how values are displayed within the interpolated string. They provide additional flexibility and control over the final output. Here's an example that demonstrates the use of formatting specifiers:

1amount = 42.56789
2formatted_amount = "The amount is %.2f" % amount
3print(formatted_amount)

In this case, the %f placeholder is used to indicate a floating-point value, while the .2 after it specifies that the output should have two decimal places. The resulting string will be:

1The amount is 42.57

String Interpolation with f-strings

Python 3.6 introduced a more concise and powerful way of performing string interpolation called f-strings. F-strings are prefixed with the letter f and allow you to embed expressions directly within the string literal. Let's see an example:

1name = "Bob"
2age = 30
3message = f"My name is {name} and I am {age} years old."
4print(message)

In this case, the expressions within the curly braces {} are evaluated and their values are inserted into the final string. The result will be identical to the first example:

1My name is Bob and I am 30 years old.

F-strings also support the use of formatting specifiers. Here's an example:

1amount = 42.56789
2formatted_amount = f"The amount is {amount:.2f}"
3print(formatted_amount)

The output will be the same as before:

1The amount is 42.57

String interpolation in Python provides a convenient way to construct dynamic strings by embedding expressions or variables within string literals. Whether you choose to use the % operator or the more modern f-strings, understanding and utilizing string interpolation can greatly enhance your code readability and efficiency.