Skip to main content

Unit 2 · Python mode... Activate! · Lesson 22 of 57

F-strings to the Rescue

Some suffering first

Gluing strings together with + works. But let's be honest, it gets ugly fast.

Rishabh wants a program that prints this:

Hey Rishabh! You're 16, so in 5 years you'll be 21, and Amer will still be using amer123.

With +, that looks like this:

name = "Rishabh"
age = 16
years = 5
password = "amer123"

print("Hey " + name + "! You're " + str(age) + ", so in " + str(years) + " years you'll be " + str(age + years) + ", and Amer will still be using " + password + ".")

Yikes. Count the quotes. Count the spaces. Count the str()s. Miss ONE space and you get you'llbe. Miss ONE str() and Python yells at you.

Try it yourself first. I promise there's a point to this suffering.

Using + (and str() wherever you need it), print exactly:

Alex is 15 and has deleted the website 3 times this week.

Use the variables, don't just type the numbers.

Python exercise

Write the program in an editor next to the lesson, run it, and have it checked automatically. Create a free account to do this part.

F-strings to the rescue!

Okay, okay. Here's the good stuff.

Meet the f-string. Put an f right before the opening quote, and now you can drop variables straight into the sentence with curly brackets {}:

print(f"Hey {name}! You're {age}, so in {years} years you'll be {age + years}, and Amer will still be using {password}.")

That's it. That's the whole thing.

  • No + everywhere
  • No str() (f-strings convert for you!)
  • The spaces are right there in the sentence, exactly where you can see them
  • You can even do math inside the {}, like {age + years}

The f stands for formatted. Inside an f-string, anything in {} gets teleported in as its value. Everything else is just regular text.

Forget the f and Python prints the curly brackets as-is: Hey {name}!. Quotes mean don't touch, remember? The f is what tells Python to look inside.

So when should you use which?

  • + for quick and dirty stuff, like "Hello " + name
  • f-strings for anything longer, especially when there are numbers in it

Now do the same sentence again, but with an f-string this time. Feel the relief.

Alex is 15 and has deleted the website 3 times this week.

Python exercise

Write the program in an editor next to the lesson, run it, and have it checked automatically. Create a free account to do this part.

Do this lesson for real

With a free account you get the terminals, challenges and checks that go with the lessons in Intro to Python, and your progress is saved as you go. CyberAcad is a 501(c)(3) nonprofit, so there is nothing to pay.