Introduction to f-strings
In this lesson, you’ll learn how to insert values, variables, or expressions directly into a string using f-strings.
Sometimes, we need to create a string that includes information stored in variables. In this example, we use the +
operator to achieve this.
This works, but it can be a bit verbose.
A more convenient and elegant way to embed variables into strings is using so called formatted string literals, or simply f-strings.
Here's the same example, but this time we use an f-string instead of the +
operator:
To create an f-string, simply add an f
before the quotation mark of your string.
To embed the value of a variable into the string, use curly braces {}
.
F-strings are are not only easier to read but also offer other useful features.
One of these is automatic type conversion.
Consider the following example.
The code throws an error because the variable age is not a string. The +
operator can only concatenate strings.
In order to make this work, we need to convert age to a string before combining it with other strings.
To do this, we can use the str()
function. It converts the integer 43
into the string '43'
:
Again, this approach can be a bit tedious.
An f-string simplifies this by automatically converting the type of our variable:
F-string are not limited to embedding variables. You can embed any Python expression.
Here, the f-string includes a mathematical expression:
You can even call a function within an f-string:
What will be the output?
What will be the output?