Skip to main content

Filling in the Blanks (f-strings)

Sometimes you want to create a sentence that includes values from variables.

Doing this with commas or + signs can look messy and hard to read:

name = "Sai"
score = 95
# Messy way:
print("Hello " + name + ", your score is " + str(score) + ".")

To make this clean and simple, Python uses f-strings (Formatted Strings).


1. How f-strings Work​

To use an f-string:

  1. Put the letter f right before the opening quotation mark of your text.
  2. Put the variable names inside curly brackets {} directly inside the text.
name = "Sai"
score = 95

# Clean f-string way:
message = f"Hello {name}, your score is {score}."
print(message)
# Output: Hello Sai, your score is 95.

When Python runs this code, it automatically replaces {name} with "Sai" and {score} with 95.


2. Formatting Numbers (Decimal places)​

You can also control how numbers look inside f-strings. For example, if you want to show a price with exactly 2 decimal places, you can add :.2f inside the curly brackets:

price = 19.995
quantity = 3

# :.2f tells Python: "Show this number with exactly 2 decimal places"
receipt = f"Total for {quantity} items: ${price * quantity:.2f}"
print(receipt)
# Output: Total for 3 items: $59.98

Quick Summary​

  • f-Strings (f"..."): The modern, Pythonic standard to embed variables directly inside text using {} placeholders.
  • Inline Expressions: Calculate math and call functions directly within curly braces (e.g., f"Total: {price * 1.18}").
  • Decimal Formatting: Format float precision cleanly with formatting specifiers (e.g., {pi:.2f}).
  • Best Practice: Always prefer f-strings over older % formatting or .format() methods for better speed and readability.

What's Next?​

Now that we know how to handle input and output, let's learn how to perform calculations, make comparisons, and build decision logic using Operators in Module 4!