Skip to main content

f-strings

Note☆ Learning Objectives
  • Construct f-strings to combine strings and other variables.
  • Format numbers in f-strings to control how many decimal places are shown.

f-strings

Formatted Strings is a powerful way of creating a templated string and inserting variables into specific positions with the created string. It’s following the syntax below:

NoteBASIC SYNTAX: f"anything {variable} anything"
  • variable is any python variable that is currently defined. It can be of any type (int, float, bool, str, etc)
  • You do not have to convert the variable to a string, that is done automatically
  • Notice that there is no space between the f and the first quote

Consider the following message: Good morning John! Your net worth is \(23,500\)

Let’s imagine that this is a generic message displayed in a program to any customer using their first name and their accounts total.

An f-string can help us create those generic messages by inserting variables as shown below. Try changing the first_name or any of the accounts values. The message should change but follow the same template:

Now notice that the account value doesn’t use a comma , to seperate the thousands. We’ll learn about formatting in the next section.

🎯 Test Myself: Use f-strings to print the following message:

I am a John Abbott student in the Science program. I am currently in semester 1. I am taking 15 credits.

You may use multiple print() statements to break it in to various lines.

school = "John Abbott"
program = "Science"
semester = 1
number_credits = 15

print(f"I am a {school} student in the {program} program." )
print(f"I am currently in semester {semester}. ")
print(f"I am taking {number_credits} credits.")

You can also create an f-string using a python expression:

NoteBASIC SYNTAX: f"anything {python code} anything"
  • python code that when evaluated, returns a value.
  • Notice that there is no space between the f and the first quote

What goes between the {} can also be a python expression such as an arithmetic operation or a comparison:

x = 3
z = f"the value of x is {x + 2}"   # OK!, prints 5
z = f"Is x equal to 5? {x == 5}"   # OK!, prints False because == is how we check for equality
WarningAn assignment is not going to work!

On the other hand, assignning a variable in an f-string will cause an error. Because this isn’t an expression, it’s an assignment which doesn’t return a value.

x = 3
z = f"Setting x to 2 {x = 2}"      # NOT OK!, x=2 does not return a value

🎯 Test Myself: Given the price of an item and the tax rate, use f-strings to print the price with taxes, without creating an additional variable:
Total: $22.4825
Don’t worry about the number of digits shown after the decimal part (yet!)

price = 19.55
tax_rate = 0.15

print(f"Total: ${price*tax_rate + price}")

Additional resources

  1. Video on f-strings