Skip to content

f-Strings

f-Strings

Python can print data back to a user in a number of ways. One of these ways is using f-strings. An f-string is a specific type of Python string pre-pended with an f that can include variables enclosed in curly braces { }. An example of a Python f-string is below:

In [1]:
a = 5
f_string = f'the number is {a}'
print(f_string)

the number is 5

A couple points to review in the short example above. First a variable, called a, is assigned the value 5. Next a new variable f_string is assigned the value f'the number is {a}'. The string f'the number is {a}' is an f-string. Notice how the letter f comes before the quotation mark that denotes the string. Inside the f-string, there is a variable enclosed in curly braces {a}. Using curly braces within a f-string inserts the value of a pre-defined variable into the string. Since a was assigned a value of 5, when f'the number is {a}' is printed, the output seen is the number is 5. Note how {a} was replaced with 5 and the output does not contain curly braces { }. We can compare the difference between a regular string and an f-string by printing out two different statements:
In [2]:
a = 5
print(f'The f-string says a is equal to {a}')
print('The regular string says a is equal to {a}')

The f-string says a is equal to 5
The regular string says a is equal to {a}

Note how the first printed line shows 'a is equal to 5' and the second printed line shows 'a is equal to {a}'. The first print line contains an f-string, so the value of a (which is 5) is shown. The second print line contains a regular string, so the value of a is not inserted and instead, we see {a}. Multiple variables can be inserted into an f-string simultaneously. These variables can be assigned as integers, floats, strings, or lists. All four data types print out when enclosed in curly braces inside an f-string.
In [3]:
a = 5           #int
b = 6.02        #float
c = 'show me'   #string
print(f'An integer is {a}, a float is {b}, and a string is {c}')

An integer is 5, a float is 6.02, and a string is show me

Expressions like 2+2 can also be placed inside f-strings. When printed, the expression inside the f-string is evaluated (4 is seen instead of 2 + 2). Functions can also be called on the inside f-strings. The function output is shown when the f-string is printed.
In [4]:
print(f'An expression {2+2}, and what is lowest of [1,2,3]? It is {min([1,2,3])}')

An expression 4, and what is lowest of [1,2,3]? It is 1

Methods placed inside the curly braces, can be part of f-strings. The str.upper() method converts a string to all uppercase. This method can be called on the inside of an f-string when it is enclosed in a set of curly braces.
In [5]:
name = 'gabby'
print(f'nice to meet you uppercase {name.upper()}')

nice to meet you uppercase GABBY

Python f-strings are a useful programming structure when users input data to a running Python program.