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.
name = 'Jane'
print('Hello, ' + name + '!')
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:
name = 'Jane'
print(f'Hello, {name}!')
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.
age = 43
print('Jane is ' + age + ' years old.')
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'
:
age = 43
print('Jane is ' + str(age) + ' years old.')
Again, this approach can be a bit tedious.
An f-string simplifies this by automatically converting the type of our variable:
age = 43
print(f'Jane is {age} years old.')
F-string are not limited to embedding variables. You can embed any Python expression.
Here, the f-string includes a mathematical expression:
print(f'10 times 12 is {10 * 12}.')
You can even call a function within an f-string:
def add(a, b):
return a + b
print(f'10 plus 12 is {add(10,12)}.')
What will be the output?
print('3 times 3 is {3 * 3}')
What will be the output?
print(f'3 times 3 is {3 * 3}')