Skip to content
dreamcode
dreamcode
Map
f-strings
Lesson 4 of 77
+15 XP on finish
PYTHON BASICSChapter 1 · Python Basics

Formatted strings

An f-string is a string with an f before the opening quote. Anything inside {curly braces} is worked out and dropped into the text, so you never glue pieces together with +. You can even format numbers: {price:.2f} always shows two decimal places.

Worked example

How it reads

  • The f before the quote switches on the braces
  • Braces can hold any expression, like {stars * 2}
  • :.2f after a value formats it with two decimal places
Common mistakes
  • Forgetting the f: Python then prints the braces literally.
  • Using the same quote inside the braces as around the string. Use ' inside a string wrapped in ".
Cloud tip: f-strings convert numbers to text for you, so there is no need for str(stars) when mixing words and numbers.
main.py
PYTHON
real Python, runs in your browser
Console
Run your code to see its output here.
YOUR TURN

Use an f-string to print exactly Mars has 2 moons, using the two variables.

Press Run to check your work.