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 equalityf-strings
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:
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.
You can also create an f-string using a python expression:
What goes between the {} can also be a python expression such as an arithmetic operation or a comparison:
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!)