Tricks to Use Python f-strings More Efficiently

F-strings are string literals that begin with a f and curly braces which contain expression which later converted into their values. The expression...
Hey .py devs!

Have you ever used the cool f-strings in your python project?

If no, then you must start using it. But before that let me clear you the following things,

  • What are f-strings in python?
  • How to use them?
  • Why use them?

After all this we will see the cool tricks we are going to talk about in this post.

So let's start learning...

Python f-strings tricks
Table of Contents

Introduction

First what is a f-string in python?

What are f-strings?

F-strings or "formatted string literals" joined the party in the python 3.6 version before that we were using the old school str.format() method.

F-strings are string literals that begin with a f and curly braces which contain expression which later converted into their values. The expressions are evaluated at runtime and then formatted using the __format__ protocol.

How to use f-strings?

Consider the following code,

>>> name = "Genius"
>>> age = 22
>>> f"Hello, {name}. You are {age}."
'Hello, Genius. You are 22.'

In the above code we used the f and then enclosed the string in quotes(""). The expressions are writtern in curly which will be replaced with their values when the program is executed.

You can also use a capital F,

>>> F"Hello, {name}. You are {age}."
'Hello, Genius. You are 22.'

Now you can start using f-strings in your code.

Why use f-strings?

As from Python 3.6, f-strings are a great 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!

Now you know what are these f-strings, let's see the tricks you can do with them.

F-strings tricks

Here we have 4 tricks that can be achieved with f-strings and if you find more let me know in the comments!

1. Formatting large Numbers

Have you noticed? Generally, while writing large numbers people use the thousands saperators.

The commas separating the numbers in group of three integers. like the number 1234567890 is written as 1,234,567,890.

Similarly in python, f-strings can be used to separate large numbers with thousand separators.

>>> # Without thousand separators
>>> number = 1234567890
>>> print(f"{number} is a large number")
1234567890 is a large number.
>>> # With thousand separators
>>> print(f"{number:,d} is a large number.")
1,234,567,890 is a large number.

In the above code we used the :,d with the variable in curly braces to separate the number with commas.

2. Format dates

We can use the f-strings to format dates. or we can specify the format the same way we did in the first trick.
We can use the dates without formatting like other variables in f-strings or represent them in a better way. Like this,

>>> # Without formatting dates
>>> from datetime import datetime
>>> today = datetime.today().date()
>>> print(f"Today is {today}")
Today is 2021-08-01

>>> # With formatting (a better representation)
>>> print(f"Today is {today:%B %d, %Y}")
Today is August 1, 2021

In this way you can represent your dates in a better format with f-strings

3. Pad Numbers

Sometimes we see seriel numbers in the form 001, 002, 003... so on. I don't know it makes sense or not to write like this but if you want such format in your code then f-strings are here to help.
In f-strings we can place any number of leading zeroes for a variable. Refer to the code below.

>>> a = 4
>>> b = 2466
>>> print(f"The numbers are \n{a:04} \n{b:04}")
The numbers are
0004
2466

Here a:04 indicates that there will be total of 4 digits and the leading blank spaces will be replaced by zeroes.

4. Writing Expressions

Not just variables but f-strings can also be used to write expressions with the literals. To save the time we can write small pieces of code etc. Which means we can perform these operations without going to a new line.
In this code we subtracted the 3 days from the date today, to get the date before 3 days.

>>> # Date manipulation
>>> from datetime import datetime
>>> today = datetime.today().date()
>>> print(f"The results were announced 3 days ago on {today - timedelta(days=3)}.")
The results were announced 3 days ago on 2021-07-29.

The above code involves use of mathematical operations with f-strings. Similarly, we can also use some methods like len() etc. in the f-strings to save time.

>>> list = [1, 3, 5 ,67, 82, 67]
>>> print(f"The list contains {len(list)} items.")
The list contains 6 items.

These are some of the advanced tricks with f-strings which help us to save time and effort in data-science or any python projects we are working on, which involve the use of f-strings. f-strings are the better syntax to format a string literal in a more consie and faster way.

If you find more tricks like this let me know in the comments.

Thank You!
Hello! Myself Tejas Mahajan. I am an Android developer, Programmer, UI/UX designer, Student and Navodayan.