The world’s leading publication for data science, AI, and ML professionals.

3 Must-Know Methods for Python String Interpolation

How about that print statement?

How about that print statement?

Photo by Jordi Moncasi on Unsplash
Photo by Jordi Moncasi on Unsplash

String interpolation is kind of embedding variables into strings. Unlike typing an entire plain string, placeholders are implemented in the string that can hold variable values.

String interpolation allows us to use the print statements more efficiently. Whether it is for debugging code or confirming the results, print statements are likely to be all over your script.

In this article, we will go over three ways used for string interpolation in Python. They can do the same thing in a different way. After going through the examples, you will probably choose your favorite way.

Formatting with placeholders

This is kind of an old method and not commonly used anymore. The "%" operator serves as the placeholder for variables.

Here is a simple example.

result = 20
print("The result is %s." % result)
The result is 20.

We can also add multiple placeholders in a string.

name = "John"
id = 22
print("Hello %s, your id is %s." % (name, id))
Hello John, your id is 22.

The letter s is used along with the % operator to indicate the placeholder. This is an old method so we will not go in detail. However, it is still important to know because you are likely to encounter code that includes strings with this method.


String formatting with .format()

It is similar to the previous method but we use curly braces instead of "%s".

result = 20
print("The result is {}".format(result))
The result is 20.
name = "John"
id = 22
print("Hello {}, your id is {}.".format(name, id))
Hello John, your id is 22.

The variables are placed into the curly braces according to their order. There is also an order associated with the curly braces that starts from 0. We can manipulate this order by writing numbers inside them.

print("Hello {1}, your id is {0}.".format(name, id))
Hello 22, your id is John.

The index 0 is associated with the name variable so it is written where the 0 index is specified.

We can also refer to each curly braces with an assigned name. In that case, the order in format does not matter.

year = 2000
price = 100000
print("The house is built in {year_built} and worth {value}"
.format(value = price, year_built = year))
The house is built in 2000 and worth 100000.

In case you are printing decimal point numbers in a string, you can adjust the number of decimal digits to be displayed.

# without adjustment
result = 1.346343454353
print("The result of is {result}".format(result = result))
The result of is 1.346343454353
# rounded up to 2 decimals
print("The result of is {result: 1.2f}".format(result = result))
The result is 1.35

In the expression "1.2f", 2 represents the number of decimals and 1 represents the size the variable holds. It is almost always used as 1 but let’s do an example with a different value to see its effect.

print("The result of is {result: 10.2f}".format(result = result))
The result of is       1.35

Formatted string literals (f-strings)

Formatted string literals, also known as f-strings, are the most recent of the three. They are introduced with Python 3.6.

F-strings use curly braces to as variable placeholders. However, we can write the variable names inside the curly braces instead of specifying them at the end.

name = "John"
id = 22
print(f"Hello {name}, your id is {id}.")
Hello John, your id is 22.

We put the letter f before the string characters to tell Python that it is an f-string.

The f-strings are more readable than the other two methods. It is also easier for developers. In case of having many variables, it becomes a tedious task to follow the variables in the string.

It is also prone to making mistakes to specify the variables at the end. What f-strings offer is clean syntax and easy-to-read code.

The floating point adjustment is available with f-strings as well.

result = 1.346343454353
print(f"The result of is {result: 1.2f}")
The result of is  1.35

If you need to modify the variables before printing, it is easier to follow such modifications with f-strings. Here is an example.

location = "Houston,TX"
price = 100000
print(f"The house is in {location[:-2]} and is worth {price * 2}")
The house is in Houston, and is worth 200000

We omit the state and double the price. It is possible with the other methods as well. However, tracking these modifications is relatively easier with f-strings especially when there are many variables.


Conclusion

We frequently use the print statement not only for confirming the results but also for debugging. String interpolation allows us for manipulating or modifying the strings to make the most out of print statements.

Although all three methods do the job, I like the f-strings better because I think it is the most practical one. At the end of the day, readability matters and f-strings are better from that perspective.

Thank you for reading. Please let me know if you have any feedback.


Related Articles