What Are Python F-Strings and How Do You Use Them?
Python makes it easy to do a lot of things. The second you believe something is going to be challenging, Python holds your hand as if to say, “Let me show you how to simplify what you’re trying to do.”
Such is the case with f-strings, which provide a simple and fast method of interpolating (inserting) and formatting strings. Using f-strings, your code will not only be cleaner but also faster to write.
With f-strings you are not only able to format strings but also print identifiers along with a value (a feature that was introduced in Python 3.8).
Before we get into this, it’s important to understand what string formatting is. We’re not talking about the formatting of text with bold, italics or underlining. String formatting makes it possible to design a string using the formatting techniques that are provided with the programming language you use. Also known as string interpolation, string formatting is the process of inserting a custom string into predefined text.
Consider a word-processing document and fields. Using fields, you can insert specific data into a document, as described by the word processor you use. Although this analogy isn’t 100% accurate, it does give you an idea of what this particular interpolation is.
Let me show you two different examples of code, one that doesn’t use f-strings and one that does. The object of the code is to simply print a sentence using two defined variables.
The first, non-f-string, code looks like this:
The output of the following code would be:
|
1 |
Hello, my name is Jack Wallen and I'm a professional Writer. |
What we’re doing is using the format() function, which inserts the variables into the proper positions marked by the curly braces. You might be able to predict the issue with this code. It’s cumbersome, which means it can lead to errors. This method of formatting a string also takes more time to write. If you’re working with a very large program, those types of statements can add up.
But what if we go the f-string route? All of a sudden, our block of code becomes considerably more concise (and less prone to errors). That same application, using f-strings, would look like this:
Run the code, and the output will be the same.
The important thing to understand about f-strings is they can do the same with less. For example, in the first block of code, you have to remember to close out the statement with the second parentheses “)”. If you forget that, the code will not run. The second example doesn’t require a second closing parentheses. Any time you can avoid even the simplest error-inducing bits, you’re taking a step forward, and f-strings help on this front.
Another cool f-string trick is the ability to print identifiers along with values. Again, this can greatly simplify your code. Take this sample bit of code:
The output of the above code would be:
|
1 |
fname = 'Jack', lname = 'Wallen' |
To do that without f-strings, the code becomes a bit more complicated:
We don’t want to have to do that.
You can also use f-strings in the evaluation of expressions, like so:
|
1 |
print(f"{10 * 10}") |
The output of the above line would be 100.
Nifty.
In the same vein, you can do things like use values and format specifiers. Let’s say you want to print out Pi but only to five decimal points. You could do that with an f-string, like so:
|
1 |
format(3.14159265359, ".5f") |
The above line would print out:
|
1 |
3.14159 |
A better example of this would be formatting a number for dollars at two decimal places. Consider these two lines of code:
Those two lines could conclude with:
|
1 |
'Balance: $10010.87' |
Or, what if you wanted to center a string within a row of asterisks? First, define the string like so:
|
1 |
name = "Jack Wallen" |
Next, we use an f-string to define how many characters the line will have in total, including the name variable. What remains will be filled with * on either side. The f-string looks like this:
|
1 |
f"{name:*^30}" |
The output would be:
|
1 |
'*********Jack Wallen**********' |
But what about calling our own defined functions using an f-string? Let’s create a new function, called salutation(). That function might look something like this:
def salutation(name):
return “Good afternoon, ” + person
What we’ve done is define a function that accepts one parameter, called person, that will be defined in the next block of code and uses an f-string with the print() function like this:
person = “Jack Wallen”
print(f”{salutation(person)}”)
Put it all together, and it looks like this:
The output of the above code would be:
|
1 |
Good afternoon, Jack Wallen |
And that’s the gist of using f-strings in Python. This method of string formatting will be very handy as you continue your journey with the Python language.