The magical python f-string

Friends DO let friends use f-strings! This addition to python was released with python 3.6, and documented on PEP-498 by Eric Smith. A welcome and brilliant addition to python!

The magical python f-string

Every single developer in this planet will have to format a string during their career, and most of us have to use string formatting on a daily basis!

Let's take a quick look at how we used to format strings, and how python f-string makes that process much easier, more organized and much simpler to read.

Traditional String Formatting in Python

If you have been using python since version 2.x, you should be familiar with at least three (sometimes more) ways to manipulate strings and string values.  Let's take a look at a few methods, how they differ from f-strings, and how f-strings are so much cleaner (and perform much better) than the alternatives.

The '%s' method

The first method that we will explore involves python's interpretation of the %s string within the string you are working on.  This is a bit challenging, as there are no indicators as to which string belongs where.  It is driven by the position of the string and the order of the parameters.

board = "Raspberry Pi"
version = 4
model = "B"
released = 2019

print("This is the %s board, version %s model %s, released on %s" % (board, version, model, released))

The addition/concatenation method

This method adds all of the strings together in an effort to build a final string.  Please note that python (unlike javascript) does not allow you to add numbers to the string, so you need to cast the version and released integers to string, see below:

board = "Raspberry Pi"
version = 4
model = "B"
released = 2019

print("This is the " + board + " board, version " + str(version) + " model " + model + ", released on " + str(released))

The string.format() method

This is slightly better, as it adds some level of organization, as well as (optionally) naming for the parameters.  This method should be familiar for developers that have experience in java, c#, and other object-oriented programming languages out there.  As you can see below, we can use the string.format in a few ways, including a sneaky way to print a dictionary object, based on its keys (P.S. this will throw a 'KeyError' exception if the key does not exist in the dictionary, but is referenced in the print statement).

board = "Raspberry Pi"
version = 4
model = "B"
released = 2019

# let's print based on the string format method
print("This is the {} board, version {} model {}, released on {}".format(board, version, model, released))

# you can also pass in the variable names on the string.format method
print("This is the {board_name} board, version {version_name} model {model}, released on {released}".format(
    board_name = board, version_name = version, model=model, released=released))

# you can also pass in a dictionary for the string.format method
sample_dict = {
    "board": board, 
    "version": version, 
    "model": model, 
    "released": released }
print("This is the {board} board, version {version} model {model}, released on {released}".format(**sample_dict))

Finally, the new python f-string comes to the rescue!

As mentioned above, python f-strings were included in python 3.6 and newer, and the full PEP can be found here:

PEP 498 -- Literal String Interpolation
The official home of the Python Programming Language

f-strings are simply amazing, as they remove the complexity of formatting the string, and yet, add a ton of power to our string manipulation commands.  See below for a few examples.  One neat example is that we can actually perform some calculations and manipulations within the string itself.  Obviously, these should be simple, display-formatting only manipulations, but in any case, they are neat!

# we will use the 'datetime' module on the last example below
from datetime import datetime as dt



board = "Raspberry Pi"
version = 4
model = "B"
released = 2019

# f-strings to the rescue
print(f"This is the {board} board, version {version} model {model}, released on {released}")

# this also works, because the 'f' is not case-sensitive
print(F"This is the {board} board, version {version} model {model}, released on {released}")

# you can perform operations in the curly mustaches!
print(f"This is the {board} board, version {version} model {model}, released on {released} ({dt.utcnow().year - released} years ago)")

gotchas!

There are a few scenarios where you need to tread carefully with f-strings, and here are a few of them:

  1. If you want to display curly mustaches, you need to double them!  Example:
    print(f"{{hello}}") will print "{hello}"
  2. If you want to display an interpreted value in curly mustaches, then you need to triple them!  Example: print(f"{{{1 + 1}}}") will print "{2}".  This is because you are telling the interpreter that you want curly mustaches (double), but there is an operation/variable to be included (additional curly mustache.)
  3. Be careful to not mismatch the quotes, which will generate an error, such as print(f"{dictionary["key"]}").  You can, instead, change the dictionary/key lookup to single quotes, such as print(f"{dictionary['key']}").

Python f-strings are just amazing, and a great addition to the language. There are so many additional uses, but I hope that this post helps you get started with it.

Thoughts? Comments? tweet @uberdronis.

cheers!


the entire script can be found in the moshpit repo within my github account, directly linked here.

Featured image created by David Clode, downloaded from unsplash, licensed under the unsplash license.