Mastering f-String Formatting

f-Strings (formatted string literals) provide a readable way to embed expressions inside string literals. They make string formatting concise and maintainable.

f-String Fundamentals

name = "Lina"
age = 28
print(f"{name} is {age} years old")
Lina is 28 years old

In this example:

  • f prefix marks an f-string
  • Variables in {} are replaced with values
  • Automatic string conversion occurs

Formatting Options

Number Formatting

pi = 3.14159
print(f"Pi: {pi:.2f}") # Two decimal places
Pi: 3.14

Expressions

print(f"Next year: {age + 1}")
Next year: 29

Practical Application: Receipt Generator

item = "Coffee"
price = 4.5
qty = 3
print(f"${qty}x {item}: ${price * qty:.2f}")
3x Coffee: $13.50
This shows:
  • Multiple variables in one string
  • Currency formatting
  • Calculations within f-strings

Common Errors

# Missing f prefix
print("{age}") → {age}
# Forgetting closing brace
print(f"{age") # SyntaxError

Your Task: Create Personalized Greeting

Using the variables name = "Ada" and age = 11:

  1. Create an f-string combining both variables
  2. Store it in the message variable
  3. Ensure output matches exactly: "Hello, Ada! You are 11 years old."

Remember: f-strings require the f prefix and use curly braces {} for variables.

Section 1/5f-String Fundamentals

f-String Fundamentals

In this example:f prefix marks an f-stringVariables in {} are replaced with valuesAutomatic string conversion occurs

Mastering f-String Formatting

f-Strings (formatted string literals) provide a readable way to embed expressions inside string literals. They make string formatting concise and maintainable.

f-String Fundamentals

name = "Lina"
age = 28
print(f"{name} is {age} years old")
Lina is 28 years old

In this example:

  • f prefix marks an f-string
  • Variables in {} are replaced with values
  • Automatic string conversion occurs

Output:

Click "Check" to run your code.