An Introduction to f-strings in Python 3

Learn how to use formatted string literals in Python
John John (304)
5 minutes

Python supports multiple ways of formatting strings, but Python 3.6 (PEP 498) introduced a new, concise way to embed expressions inside of strings literals. The feature is called f-strings, which stands for "formatted string literals".

The goal of the f-string syntax is to provide a concise way to embed Python expressions inside of a string literal. These expressions are not fixed values, but rather evaluated at runtime.

In this guide, we'll learn how to use f-strings.

Posted in these interests:
h/python67 guides
h/code69 guides

An f-string is a string literal prefixed with f. In the following example, we'll simply embed a variable into a string:

>>> name = 'John'
>>> f'Hello, {name}'
'Hello, John'

Since f-strings allow us to evaluate expressions at runtime, we can do interesting things like use arithmetic operators or execute functions.


Joining items in a list
>>> people = ['Debbie', 'Junia', 'Ruth']
>>> f'Names: {", ".join(people)}.'
'Names: Debbie, Junia, Ruth.'
Arithmetic and rounding
>>> before = 7
>>> after = 10
>>> f'The percentage change is: {round(after / before - 1, 2)}%'
'The percentage change is: 0.43%'
Accessing elements in a list or dictionary
>>> my_dict = {'name': 'Luke'}
>>> my_list = [0, 1, 2]
>>> f'{my_dict["name"]} {my_list[2]}'
'Luke 2'

Conversions allow us to "convert" a value before formatting it. Conversions are introduced by an exclamation point ! followed by a letter representing the conversion type.

The following conversions are available:

Conversion Function called
!s str()
!r repr()
!a ascii()


str conversion

By default, values are converted to strings before formatting, so string conversion is the default behavior. But to explicitly use string conversion, the syntax would be:

>>> name = 'John'
>>> f'My name is {name!s}'
'My name is John'
repr conversion
>>> name = 'John'
>>> f'My name is {name!r}'
"My name is 'John'"
ascii conversion
>>> name = 'ийя'
>>> f'My name is {name!a}'
"My name is '\\u0438\\u0439\\u044f'"

The result of each embedded expression is formatted using Python's "formatting specification". So, the formatting rules are the same as what you might be used to with the format function.


Fill with leading zeros
>>> number = 2
>>> f'My number is: {number:02}.'
'The number is: 02.'

Filling with anything other than zero requires an alignment flag (> or <).

>>> status = 5
>>> f'{status:x<3}'
Rounding decimals
>>> total = decimal.Decimal('10.123456')
>>> f'The total value is: {value:.4}.'
'The total value is: 10.12.'
Separating thousands with commas
>>> population = 12500345
>>> print(f'The population is: {population:,}.')
'The population is: 12,500,345.'
Printing datetimes
>>> today = datetime.datetime(year=2019, month=11, day=5)
>>> f'{today:%B %d, %Y}'
' November 05, 2019'

These are just a few examples of special formatting rules. See the formatting specification docs for more details.

It's worth making one quick note about curly braces. Since the expressions are encapsulated by curly braces, if you want to actually display a curly brace, you'll have to use double braces. Like this:

>>> f'Here is a real curly brace : {{'
'Here is a real curly brace : {'

At this point, we've covered f-strings in detail. If you feel like something was missing or if you have any questions, please let me know in the comments below!

Don't let bad strings string you along.
Tayler Tayler (75)

When it comes to replacing the strings on your ukulele there are a ton of factors to keep in mind, but—don't worry—I won't string you along too much as I break down the art of picking your next pair.