Suppose you want to output a person's name and profession. You could write a simple program as follows.
# Define variables
name ='Mark'
profession ='Astronaut'
age =7# Output info
output_string =('My name is '+ name +', I am '+str(age)+' years old '+'and my profession is '+ profession +'.')print(output_string)
My name is Mark, I am 7 years old and my profession is Astronaut.Powered by
That approach lacks conciseness and readability. Fortunately, string interpolation offers a better solution. It allows variables, expressions, or function outputs to be inserted directly into a string, making string manipulation dynamic and eliminating the need for manual concatenation.
Using a string interpolation approach, we could rewrite the code as follows.
# Define variables
name ='Mark'
profession ='Astronaut'
age =7# Output info
output_string =f'My name is {name}, I am {age} years old and my profession is {profession}.'print(output_string)
My name is Mark, I am 7 years old and my profession is Astronaut.Powered by
The version with string interpolation allows for embedding expressions directly inside of the string without the use of messy concatenations. As you can see, it is a much cleaner approach.
Basic String Interpolation in Python
There are several different string interpolation techniques available in Python. The most commonly recommended method is formatted string literals, also known as f-strings, which have been available since Python 3.6.
Another method, commonly seen in code older than Python 3.6, is the .format() method. Although this method is more verbose than f-strings, it occasionally has advantages (details below).
Finally, you may encounter %-style formatting in legacy code.
Using f-strings (Python 3.6+)
f-strings (formatted string literals) are a powerful and concise way to format strings in Python. They were introduced in Python 3.6 and provide a readable and efficient way to insert variables, expressions, and function calls directly into strings.
A simple example of the basic syntax of an f-string is as follows.
name ='Mark'
output_string =f'My name is {name}.'print(output_string)
In this code, the output_string variable is assigned an f-string. The f prefix before the opening quote indicates that the string supports embedded expressions. The variable name is evaluated and its value is inserted into the string, resulting in the output: "My name is Mark."
Not only variable values, but also calculations or expressions may be inserted into f-strings. Consider this example.
import math
a =3.0
b =4.0# Use string interpolation for the formulaprint(f'The hypotenuse of a triangle with base {a} and side {b} is {math.sqrt(a **2+ b **2)}.')
The hypotenuse of a triangle with base 3.0 and side 4.0 is 5.0.Powered by
The expression math.sqrt(a ** 2 + b ** 2) is evaluated directly within the string, eliminating the need to compute the value separately before inserting it into the string.
Using the .format() method
Like f-strings, the .format() method allows inserting variables and expressions into a string. The basic syntax of the .format() method is as follows.
name ='Mark'
output_string ='My name is {}.'.format(name)print(output_string)
The curly brackets {} serve as a placeholder, signaling that a variable's value will be inserted into the string at that position. The specific variable's value inserted into the placeholder is determined by the argument provided to the .format() method.
Positional arguments
What happens if you need multiple placeholders for multiple variables? Consider the following code.
name ='Mark'
age =7# The placeholders are filled in order of the arguments
output_string ='My name is {} and I am {} years old.'.format(name, age)print(output_string)
In this example, two variables, name and age, are needed. Consequently, the string includes two placeholders, and the variables are inserted in the same order they appear in the .format() method. These arguments are known as *positional* arguments because their placement in the string is determined by their position in the method’s argument list.
Indexed and named placeholders
As a variation of the placeholder idea, consider this example.
name ='Mark'
age =7# Print age twice
output_string ='My name is {} and I am {} years old. My twin brother is also {} years old.'.format(name, age, age)print(output_string)
My name is Mark and I am 7 years old. My twin brother is also 7 years old.Powered by
Here, we reused the value of the variable age twice. Including the same variable multiple times like this is clunky and detracts from readability. Is there a way to reuse a variable in string formatted with the .format() method without repeating it? Yes, there is, using so-called *indexed placeholders*.
name ='Mark'
age =7# Use indexed placeholders
output_string ='My name is {0} and I am {1} years old. My twin brother is also {1} years old.'.format(name, age)print(output_string)
My name is Mark and I am 7 years old. My twin brother is also 7 years old.Powered by
In this example, we explicitly defined the order of variables within the curly brackets, following Python’s zero-based indexing. Additionally, we reused the variable at index 1 instead of repeating it.
As an alternative to positional indexing, you can also use named arguments, where each argument is given a name.
print('My name is {name} and I am {age} years old.'.format(name='Mark', age=7))
The named argument is evaluated within the curly brackets that specify its name. As a result, the {name} placeholder is replaced with the value "Mark", and the {age} placeholder is replaced with 30.
Using the % operator
The final method for string interpolation is the % operator. It functions similarly to the printf() command in C. Its use is deprecated and strongly discouraged in favor of f-strings or the .format() method. It is mentioned here because you may encounter it in legacy codebases.
The basic format for the % operator is: "format string" % values. The format string contains placeholders, such as %s for strings, that get replaced by values. For example, the following example prints "Hello, Mark."
Other common format specifiers are shown in the following table.
Specifier
Meaning
Example
%s
String
"Hello %s" % "Alice" → "Hello Alice"
%d
Integer (Decimal)
"Age: %d" % 25 → "Age: 25"
%f
Float (Default 6 decimals)
"Pi: %f" % 3.14159 → "Pi: 3.141590"
%.nf
Float (n decimal places)
"%.2f" % 3.14159 → "3.14"
%x
Hexadecimal (lowercase)
"%x" % 255 → "ff"
%X
Hexadecimal (uppercase)
"%X" % 255 → "FF"
%o
Octal
"%o" % 255 → "377"
The % operator has many limitations. For one thing, it is less readable than f-strings. Consider the following code.
name ="Alice"
age =30
height =5.6# The % operator is hard to scan
message ="My name is %s, I am %d years old, and my height is %.1f feet."%(name, age, height)print(message)
Suppose you want to output a person's name and profession. You could write a simple program as follows.
That approach lacks conciseness and readability. Fortunately, string interpolation offers a better solution. It allows variables, expressions, or function outputs to be inserted directly into a string, making string manipulation dynamic and eliminating the need for manual concatenation.
Using a string interpolation approach, we could rewrite the code as follows.
The version with string interpolation allows for embedding expressions directly inside of the string without the use of messy concatenations. As you can see, it is a much cleaner approach.
Basic String Interpolation in Python
There are several different string interpolation techniques available in Python. The most commonly recommended method is formatted string literals, also known as f-strings, which have been available since Python 3.6.
Another method, commonly seen in code older than Python 3.6, is the
.format()method. Although this method is more verbose than f-strings, it occasionally has advantages (details below).Finally, you may encounter
%-style formatting in legacy code.Using f-strings (Python 3.6+)
f-strings (formatted string literals) are a powerful and concise way to format strings in Python. They were introduced in Python 3.6 and provide a readable and efficient way to insert variables, expressions, and function calls directly into strings.
A simple example of the basic syntax of an f-string is as follows.
In this code, the
output_stringvariable is assigned an f-string. Thefprefix before the opening quote indicates that the string supports embedded expressions. The variablenameis evaluated and its value is inserted into the string, resulting in the output:"My name is Mark."Not only variable values, but also calculations or expressions may be inserted into f-strings. Consider this example.
The expression
math.sqrt(a ** 2 + b ** 2)is evaluated directly within the string, eliminating the need to compute the value separately before inserting it into the string.Using the .format() method
Like f-strings, the
.format()method allows inserting variables and expressions into a string. The basic syntax of the.format()method is as follows.The curly brackets
{}serve as a placeholder, signaling that a variable's value will be inserted into the string at that position. The specific variable's value inserted into the placeholder is determined by the argument provided to the.format()method.Positional arguments
What happens if you need multiple placeholders for multiple variables? Consider the following code.
In this example, two variables,
nameandage, are needed. Consequently, the string includes two placeholders, and the variables are inserted in the same order they appear in the.format()method. These arguments are known as *positional* arguments because their placement in the string is determined by their position in the method’s argument list.Indexed and named placeholders
As a variation of the placeholder idea, consider this example.
Here, we reused the value of the variable
agetwice. Including the same variable multiple times like this is clunky and detracts from readability. Is there a way to reuse a variable in string formatted with the.format()method without repeating it? Yes, there is, using so-called *indexed placeholders*.In this example, we explicitly defined the order of variables within the curly brackets, following Python’s zero-based indexing. Additionally, we reused the variable at index 1 instead of repeating it.
As an alternative to positional indexing, you can also use named arguments, where each argument is given a name.
The named argument is evaluated within the curly brackets that specify its name. As a result, the
{name}placeholder is replaced with the value"Mark", and the{age}placeholder is replaced with30.Using the % operator
The final method for string interpolation is the
%operator. It functions similarly to theprintf()command in C. Its use is deprecated and strongly discouraged in favor of f-strings or the.format()method. It is mentioned here because you may encounter it in legacy codebases.The basic format for the
%operator is:"format string" % values. The format string contains placeholders, such as%sfor strings, that get replaced by values. For example, the following example prints "Hello, Mark."Other common format specifiers are shown in the following table.
Specifier
Meaning
Example
%s
String
"Hello %s" % "Alice" → "Hello Alice"
%d
Integer (Decimal)
"Age: %d" % 25 → "Age: 25"
%f
Float (Default 6 decimals)
"Pi: %f" % 3.14159 → "Pi: 3.141590"
%.nf
Float (n decimal places)
"%.2f" % 3.14159 → "3.14"
%x
Hexadecimal (lowercase)
"%x" % 255 → "ff"
%X
Hexadecimal (uppercase)
"%X" % 255 → "FF"
%o
Octal
"%o" % 255 → "377"
The % operator has many limitations. For one thing, it is less readable than f-strings. Consider the following code.