Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

F-strings

Joining text with + works, but with more values, it becomes hard to read: every number needs str(), and it's easy to forget a space or a quote:

first_name = "Anna"
age = 25
print("My name is " + first_name + " and I am " + str(age) + " years old.")

There is an easier way: an f-string. It's text with the letter f right before the opening quote. You insert a value into it by writing it in curly braces {}:

first_name = "Anna"
age = 25
print(f"My name is {first_name} and I am {age} years old.")

Both examples print:

My name is Anna and I am 25 years old.

Python replaces every {...} with the value inside it, and numbers work without str(). The spaces are part of the text, so you can see right away where they are. The f stands for “formatted”.

You can even put a calculation inside the braces:

price = 120
print(f"Two tickets cost {price * 2} dollars.")

This prints:

Two tickets cost 240 dollars.

Don't forget the f. Without it, the braces are just text, and they are printed as they are:

day = "Monday"
print("Today is {day}.")

This prints:

Today is {day}.

An f-string is a string like any other, so you can also store it in a variable. From now on, we'll use f-strings whenever we put values into text.

Instructions

  1. 1

    Create a variable forecast with an f-string that inserts the values of day and temperature into the text On Monday it will be 25 degrees.

    In the text, replace Monday with {day} and 25 with {temperature}.

  2. 2

    Print forecast. The output should be On Monday it will be 25 degrees.

  3. 3

    On the next line, print the forecast for the following day, when it will be 2 degrees warmer. Use an f-string with a calculation inside the braces, so that the program prints A day later it will be 27 degrees.

Back

10/15

  1. 1. Printing
  2. 2. Arithmetic Operations
  3. 3. Quiz: Order of Operations
  4. 4. Comments
  5. 5. Variables
  6. 6. Changing a Variable's Value
  7. 7. Division and Remainder
  8. 8. Joining Text
  9. 9. Text and Numbers
  10. 10. F-strings
  11. 11. Reading Errors
  12. 12. Quiz: Spot the Mistake
  13. 13. Quiz: Changing a Variable
  14. 14. Quiz: The Order of Commands
  15. 15. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.