Loading...

Python f-Strings

An f before the opening quote tells Python to read names inside braces. guest holds lida. f"{guest}" writes lida. The quotes still mark text. The f marks the places where a stored value should appear. The name itself is not changed.

With f, then without f

python
guest = "lida"
print(f"{guest}")
print("{guest}")

The first line is lida. The second line is {guest}. Without the f, the braces and the letters guest are ordinary characters. Python does not look up the name.

The f sits against the quote. A space between f and the quote is not this mark, and the program stops.

You write the space

drink holds tea. f"{guest} {drink}" writes lida tea. The space between the two pairs of braces is a character you typed, the same way a space string sat between names on the joining page. f"{guest}{drink}" would write lidatea, because nothing was typed between them.

Two names and a space you type

python
guest = "lida"
drink = "tea"
print(f"{guest} {drink}")

Each row is the same stored names. guest holds lida. drink holds tea. Only the writing of the print changes.

📊 What the f changes

You write print writes
f"{guest}" lida
"{guest}" {guest}
f"{guest} {drink}" lida tea

The stored text stays

print does not replace what guest holds. After these lines, guest is still lida and drink is still tea. The f-string builds a new line for that print. Empty braces, f"{}", stop the program: there is no name inside to read.

Left for the next page

This page does not cut the text by position, does not change case, and does not add numbers. The next page cuts a string by where the characters sit. The f stays a way to place a name inside text.

Check yourself

  1. guest holds lida. f"{guest}" writes lida.
  2. "{guest}" writes {guest}.
  3. f"{guest} {drink}" writes lida tea.
  4. f"{guest}{drink}" writes lidatea.

Misses

  • Expecting {guest} on the screen from f"{guest}"
  • Expecting lida from "{guest}"
  • Forgetting the f
  • Forgetting the space and then wondering why the words touched
  • Thinking the print replaced the stored name

Keep

  • f before the quote reads names inside braces.
  • f"{guest}" writes lida. "{guest}" writes {guest}.
  • f"{guest} {drink}" writes lida tea. You type the space.
  • The stored names stay as they were.
  • The next page cuts text by position.

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

❓
4
Questions
🎯
70%
To Pass
♾️
∞
Time
🔄
∞
Attempts

📝 Instructions

  • Read each question carefully
  • Select the best answer for each question
  • You can retake the quiz as many times as you want
  • Your progress will be shown at the top