Guide to String Formatting in Python Using F-Strings

Take string formatting to the next level in Python using f-strings. They provide a better way to format strings and make debugging easier, too.

Written by Frank Andrade
Published on Mar. 14, 2023
Image: Shutterstock / Built In
Image: Shutterstock / Built In
Brand Studio Logo

If you’ve been practicing Python for a while, you likely use " " to create strings in Python.

There’s nothing wrong with that. After all, our first line of Python code was a simple print(“Hello World”). That said, if you want to take your Python strings to the next level, you should use f-strings. 

What Is Python F-String?

F-string is a way to format strings in Python. It was introduced in Python 3.6 and aims to make it easier for users to add variables, comma separators, do padding with zeros and date format. 

Python String.
Python String. | Image: Frank Andrade

F-string was introduced in Python 3.6 and provides a better way to format strings. In this guide, we’ll see how to format strings in Python using f-string. We’ll also learn how to add variables, comma separators, right/left padding with zeros, dates and more.

 

How to Format With Python F-String

To follow this tutorial, make sure you have Python 3.6 or above. Otherwise, f-strings won’t work.

 

Simple Formating With F-String

F-string provides a better syntax for adding variables to strings.

Let’s print two messages using f-string in Python. To do that, we have to add the f in front of the ‘’ that we use to create regular strings. We also have to add {} to insert a variable in our string.

age = 20
python_version = 3.8

>>> print(f'Your age is {age}')
Your age is 20
>>> print(f'python_version={python_version}')
python_version=3.8

As you can see, using f-string to add variables is simpler than using regular strings and the + operator.

F-string also makes debugging easier too. Instead of printing the variable name and its value, as we did above for the python_version, we only need to write this inside the f-string: {variable_name=}

age = 20
python_version = 3.8
>>> print(f'{age=}')
age=20
>>> print(f'{python_version=}')
python_version=3.8

Now, let’s see more advanced formatting. For the following sections, we’ll be using the syntax below:

Syntax: {:[width][.precision][type]}
Type:
d: integers
f: floating point numbers
*You need to specify precision only in case of floating point numbers

More on Python: 5 Types of Arguments in Python Function Definitions

 

How to Align With Python F-String

There are very few occasions when you’d need to align a word or text to the right or left, but this is the foundation to fully understanding how to add zeros to the left or right of a number. F-string is very useful when formatting numbers.

 

Align to the Right

Say we have a number, and we want to align it to the right. We can do that using the syntax above. In this case, we only need to add the width element.

If we want to add six blank spaces and align our text to the right, we only need to add a width of eight. The default behavior is to align the text to the right.

number = 20
>>> print(f'{number}')
20
>>> print(f'{number:8}')
      20
>>> print(f'{number:>8}')
      20

If we want to be more specific, we can add the >, which indicates that the text should be aligned to the right.

 

Align to the Left

Now, let’s align our text to the left using _ as our padding character.

number = 20
>>> print(f'{number:<8}')
20      
>>> print(f'{number:_<8}')
20______

To complete the width of eight, we added six “_” using the code above.

 

How to Pad With Zeros Using Python F-Strings

Now, it’s time to use what we’ve learned in the previous section to format numbers with zeros to the left/right.

 

Right Padding With Zeros

As we’ve seen before, we can pick the padding character. In this case, we’ll choose the 0 as our padding character to have five decimals in our float below.

x = 20.123
>>> print(f'{x:0<8}')
20.12300

This is cool, but sometimes using the width makes things complicated because we have to calculate the final width of our number after adding the zeros.

It’s simpler to think of the number of decimals we want instead. We can get this using .precision from the syntax shown before. Let’s add zeros until we have five decimals.

>>> print(f'{x:.5f}')
20.12300

In the code above, 5 represents the precision and f stands for floating point numbers.

 

Left Padding With Zeros

Now, let’s add zeros to the left. This is very useful when we need to create customized formats using numbers.

Say we want to obtain the following format: YYYYMMDD, and we have regular numbers from one-to-nine. In this case, we’ll need to add zeros to the left of the month and day.

Here are the two ways to do this with f-string.

year = 2022
month = 1
day = 5

# YYYYMMDD
>>> print(f'{year}{month:0>2}{day:0>2}')
20220105
>>> print(f'{year}{month:02d}{day:02d}')
20220105

 

How to Round Float With Python F-Strings

Round Float to “n” Decimals

When it comes to rounding float numbers to “n” decimals, it’s more practical to use the .precision with f type.

Let’s round the number below to one decimal.

x = 20.123
>>> print(f'{x:.1f}')
20.1
A tutorial on how to use Python f-string. | Video: Corey Schafer

More on Python: 10 Python Cheat Sheets Every Developer Should Know

 

Format Float to Percentages

Now, let’s round the number and add the % sign.

x = 20.123
>>> print(f'{x:.1f}%')
20.1%

 

Use Commas as Thousands Separator

We can also add a comma as a thousands separator. We only need to add ,.

x = 1000000
>>> print(f'{x:,}')
1,000,000

 

How to Date Format With Python F-Strings

Last but not least, we can import datetime and use the special characters inside our f-string to get proper date formatting.

import datetime
now = datetime.datetime.now()

>>> print(f'Today is {now:%B} {now:%-d}, {now:%Y}')
Today is May 20, 2022
>>> print(f'{now=:%m-%d-%Y}')
now=05-20-2022

Here’s a cheat sheet with more characters that you can use to format date variables in Python.

Explore Job Matches.