The Serpent

// Cursing the Internet since 1998

Python f-strings Rock

Posted April 8, 2022 Code

Python is an incredible language. I moved over to it in the mid 2000’s after realising that C++ was a full time job. Since I’m no professional developer, I wanted something that could produce results rapidly, without much of a learning curve. Python was a great fit at the time (we didn’t have these fancy new languages like Go, Rust and Ruby on Rails etc!)

One of the coolest features to be released recently in Python 3.6 is the use of f-string literals, defined in PEP-498.

To see its power, let’s look at the old way to include variables in string literals, using str.format():

name = "Jo"
age = 24

print("Hello {0}, your age is: {1}".format(name, age))

While this works for a small amount of variables, it doesn’t scale particularly well, and can easily become quite messy. Let’s look at how we can use f-strings to reference the variables we need inline:

name = "Jo"
age = 24

print(f"Hello {name}, your age is: {age}")

By declaring the variable passed to print() as an f-string (using f at the start of the statement), we are now able to evaluate the string inline. This can be really useful, especially for evaluating expressions inline:

name = "Jo"
age = 24

print(f"Hello {name}, your age is in two years will be: {age+2}")

Because f-strings accept any form of Python expression, they can reference dictionaries and other structures:

car = {
    'make' : 'bmw',
    'model': '4 Series'
}

print(f"Car Make is : {car['make']}, model is {car['model']}")

So while they aren’t a complete replacement for format(), they certainly make outputting data much easier. I highly recommend checking them out if you’re still relying on format() for the majority of your code.

Python f-strings Rock
Posted April 8, 2022
Written by John Payne