Using interpolated format strings in Python

The release of Python 3.6 came with exciting functionalities. I want to speak about the feature called interpolated format string – f-strings for short- through this quick post. This new feature allows us to have a more readable, concise and even faster way of formatting string, in short words: pythonic code.

One of the most interesting features associated with the f-string is the capacity to include expressions which can be solved. The Python syntax is:

f "{variable or expression here}"

As you can observe, it is simple compared to previous functions, and it is less prone to commit mistakes as can happen when you depend on the order of the variables such as string.format syntax. As I mentioned above, using F-strings also enables you to put a full Python expression within the
placeholder braces. See the following example:

# Evaluating expressions internally
baseball_teams = [
('Arizona Diamondbacks',1),
('Detroit Tigers', 4),
('Cincinnati Reds', 10),
]

for i, (item, count) in enumerate(baseball_teams):
    f_string = f'Row {i+1}: {item.title():<20s} = {count}'
    print(f_string)

It is interesting to remark on the capacity to include a format function inside of placeholder braces too. In this example, we formatted the length of the variable .. more explanation. By default, f-string use __str__(). Nonetheless, you could use __repr__() which can be helpful in case you want to get the parable string representation of an object; you only need to include the conversion flag !r as in this example:

key = 'variable'
value = 1.2345

f_string = f'{key !r:<10} = {value: .2f}'
print(f_string)

As in the previous example, you are able to apply a format to variables parsed, including the number of digits after the decimal, justification on the string, etc. You can find more details about it here.

Finally, the following example shows you the speed of both approaches. We are using a library called timeit, its usage is simple and consists in supplying a statement of the number of iterations to be executed.

import timeit

testcode_traditional = ''' 
name = "Octavio"
age = 24
'%s is %s.' % (name, age)
'''

testcode_fstring = ''' 
name = "Octavio"
age = 24
f'{name} is {age}.'
'''

print(timeit.timeit(stmt=testcode_traditional, number=10000))
print(timeit.timeit(stmt=testcode_fstring, number=10000))

Once you execute, please observe the time delta between both options and you will have an additional reason to start using f-string over any older approach. Last but not least, thanks to my colleague and large landowner Esteban (SRE rockstar) at Languagewire for sharing this syntax. Happy coding!

geohernandez

Share
Published by
geohernandez
Tags: f-string

Recent Posts

Formatting our Postgres scripts with pgformatter in DBeaver

Are you a PostgreSQL enthusiast using DBeaver on a Windows Platform? If you find yourself…

4 months ago

Looking back to Kimball’s approach to Data Warehousing

Over time, it's fascinating to witness how certain concepts, approaches, or visions age. Time, in…

5 months ago

List Comprehension and Walrus operator in Python

When we are working with lists, dictionaries, and sets in Python, we have a special…

9 months ago

Playing with some Pandas functions and Airflow operators

Recently, I was dealing with a task where I had to import raw information into…

11 months ago

Getting the last modified directory with Python

Working with os paths is a prevalent task, especially when working on a console application…

1 year ago

First steps for configuring SQL Server with Docker

Sometimes, our working habits could experiment some interesting changes, maybe forced by real needs or…

2 years ago