Strings II

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 + '!')
Python
Output

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}!')
Python
Output

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.')
Python
Output

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.')
Python
Output

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.')
Python
Output

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}.')
Python
Output

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)}.')
Python
Output

What will be the output?

print('3 times 3 is {3 * 3}')
Python

What will be the output?

print(f'3 times 3 is {3 * 3}')
Python