Member-only story

Grok Python’s Powerful f-strings

John Clark Craig
5 min readMay 3, 2022

The advantages of using f-strings should not be overlooked!

Photo by Andreas Klassen on Unsplash

Python is known for its concise, readable, and efficient syntax. With the addition of f-strings starting with Python 3.6, this is truer than ever. Even if you have already upgraded your skill set to include the use of f-strings, here are a few nuggets of knowledge you might have missed.

Old School format()

Here’s an example of the “old way” of formatting data into strings, using the format() method. In this simple case we’ll build a string that contains some descriptive text and a numerical value.

x = 3.1416
s = "Pi is about {}".format(x)
print(s) # Pi is about 3.1416

Notice that the curly braces hold the place in the string where the format() method inserts the value of x. Multiple sets of curly braces can be used, and they need to match up with each parameter passed to the format() method.

f-strings To the Rescue

Here’s an equivalent code snippet, where a simple f-string creates the same result.

x = 3.1416
s = f"Pi is about {x}"
print(s) # Pi is about 3.1416

The “f” prefix to the string turns it into an f-string, causing whatever is placed inside any curly braces to be calculated, and its…

--

--

John Clark Craig
John Clark Craig

Written by John Clark Craig

Author, inventor, entrepreneur — passionate about alternate energy, technology, UFOs, and how Python programming can help you hack your life.

Responses (1)