Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Python 3's F-Strings: An Improved String Formatting Syntax
As of Python 3.6, f-strings are a great new way to format strings. Not only are they more readable, more concise, and less prone to error than other ways of formatting, but they are also faster!
By the end of this article, you will learn how and why to start using f-strings today.
But first, here’s what life was like before f-strings, back when you had to walk to school uphill both ways in the snow.
Take the Quiz: Test your knowledge with our interactive “Python F-Strings” quiz. Upon completion you will receive a score so you can track your learning progress over time:
“Old-school” String Formatting in Python
Before Python 3.6, you had two main ways of embedding Python expressions inside string literals for formatting: %-formatting and str.format(). You’re about to see how to use them and what their limitations are.
Option #1: %-formatting
This is the OG of Python formatting and has been in the language since the very beginning. You can read more in the Python docs. Keep in mind that %-formatting is not recommended by the docs, which contain the following note:
“The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly).
Using the newer formatted string literals or the
str.format()interface helps avoid these errors. These alternatives also provide more powerful, flexible and extensible approaches to formatting text.” (Source)
How to Use %-formatting
String objects have a built-in operation using the % operator, which you can use to format strings. Here’s what that looks like in practice:
>>> name = "Eric"
>>> "Hello, %s." % name
'Hello, Eric.'
In order to insert more than one variable, you must use a tuple of those variables. Here’s how you would do that:
>>> name = "Eric"
>>> age = 74
>>> "Hello, %s. You are %s." % (name, age)
'Hello Eric. You are 74.'
Why %-formatting Isn’t Great
The code examples that you just saw above are readable enough. However, once you start using several parameters and longer strings, your code will quickly become much less easily readable. Things are starting to look a little messy already:
>>> first_name = "Eric"
>>> last_name = "Idle"
>>> age = 74
>>> profession = "comedian"
>>> affiliation = "Monty Python"
>>> "Hello, %s %s. You are %s. You are a %s. You were a member of %s." % (first_name,