Quick Guide to Python F-Strings

If you’ve moved to Python 3.6+ but haven’t yet taken advantage of f-strings, this quick guide will run you through what they are, how to use them, and provide some some common examples you can incorporate in to your projects.

What are f-strings?

Introduced in Python 3.6, f-strings (or ‘formatted string literals’) are a method of formatting strings introduced to address some of the shortcomings of previous formatting methods (using % with a tuple appended, or using format() which was introduced in 3.0).

We can use f-strings to make our code more readable and concise, without any performance sacrifice - most tests typically indicate that f-strings are marginally faster than previous methods (check out this StackOverflow post for some tests you can replicate yourself).

Before we jump in, one common misconception with f-strings is that you should change all of your code to use them, before the other methods disappear - but this is wrong. In the PEP that introduced f-strings, it is noted that:

This PEP does not propose to remove or deprecate any of the existing string formatting mechanisms.

We’ll look at this later, as sometimes it can make sense to use other formatting methods instead of an f-string.

Basic Usage

At first, syntactically, f-strings do not seem too dissimilar from the format() command, simply with the variables shifted to being inside the string itself:

>>> name = 'dan'

>>> 'Your name is {}'.format(name)
'Your name is dan'

>>> f'Your name is {name}'
'Your name is dan'

>>> F'Your name is {name}'
'Your name is dan'

Note that we can use either an upper or lower case f to prepend our string.

This is an oversimplification, as we can also name variables within the brackets of a format() string and then name them as parameters, but ultimately the use of f-strings usually results in cleaner, more readable code.

Evaluating Expressions

Much like with the format() command, we can use any valid expression that evaluates at runtime, for example:

>>> num = 4

>>> f'The number is {num ** 2}'
'The number is 16'

>>> f'The number is {"even" if num % 2 == 0 else "odd"}'
'The number is even'

Note that we use either ‘ or “ for the outer wrapping string, and the inner expression.

We can also call functions or methods, like so:

>>> dw = 'danwalker.com'

>>> f'BE SURE TO VISIT {site.upper()}'

>>> def urlify(site):
...     return f'https://{site}'
>>> f'be sure to visit {urlify(dw)}'
'be sure to visit https://danwalker.com'

Numerical Formatting

One of the most common uses of f-strings is the ability to easily format numbers on the fly, for example, setting number precision of floating point numbers by using a colon, followed by a period, the precision, and the letter f:

>>> num = 1.3333337

>>> f'{num:.2f}'

>>> f'{num:.4f}'

>>> f'{num:.6f}'

Thousands Separator

If we’re display numbers that will be read by human beings, we can use a character after the colon which will be used as a thousands separator (a comma is typical, but we can use other symbols):

>>> num = 123456789

>>> f'{num:,}'

>>> f'{num:_}'

Adding Leading Zeros

Adding leading zeros is easy, we simply append :0x to the end of the variable name, where x is intended length of the number.

>>> num = 5

>>> f'{num:05}'

>>> f'{num:010}'

# if we don't start with a 0, we pad with spaces
>>> f'{num:15}'
'              5'

Scientific Notation

Displaying numbers in scientification notation formatting is possible by using e (or E), and we can couple it with the numerical formatting syntax to control precision:

>>> num = 123456789.987654321

>>> f'{num:e}'

>>> f'{num:E}'

>>> f'{num:.2e}' # with precision


Something most people have probably done at some point in a Python script is calculated a percentage. When displaying a percentage, Python will multiply the provided input by 100, and add a percentage sign. As always, we can also choose to control precision of the result:

>>> tasks_total = 35
>>> tasks_complete = 20
>>> percent_complete = tasks_complete / tasks_total
>>> percent_complete

>>> f'Task completion status: {percent_complete:%} completed'
'Task completion status: 57.142857% completed'

>>> f'Task completion status: {percent_complete:.2%} completed'
'Task completion status: 57.14% completed'

>>> f'Task completion status: {percent_complete:.0%} completed'
'Task completion status: 57% completed'

Hex, Binary, Octal, and Decimal

We can convert integers in to different bases with the following options:

  • b - Binary
  • o - Octal
  • x or X - Hex (outputs in lower or upper)
  • d - Decimal
>>> num = 1234

>>> f'{num:b}'
>>> f'{num:o}'
>>> f'{num:x}'
>>> f'{num:X}'
>>> f'{num:d}'


We can display the contents of dictionaries as a whole, or by referring to their key. Something to bear in mind is that you will need to use different types of quotes for the outer string, and for the dictionary elements, as such:

>>> people = {'foo': 'bar', 'asd': 'def'}
>>> f'First person is {people['foo'])'
  File "<stdin>", line 1
    f'First person is {people['foo'])'
SyntaxError: invalid syntax

>>> f'First person value is {people["foo"]}'
'First person value is bar'

An alternative is to use triple quotes:

>>> f'''First person value is {people['foo']}'''
'First person value is bar'

Which way round you to choose to use single and double quotes is up to you, however, the PEP standards


Escaping Characters

Object Strings



Multi-line Strings