Course Progress10% complete
🐍 Python Basics Topic 10 / 100
⏱ 8 min read

String Formatting

f-strings and .format() — inserting variables and expressions cleanly into text. The modern way Python handles dynamic messages.

"f-strings are one of Python's most beautiful features. They make your code read like a sentence."

— ShurAI

The Problem — Why Formatting?

When you want to include variable values inside a message, the naive approach using + is messy and breaks easily:

python — the messy way
name  = "Riya"
score = 95

# Ugly — must convert score to str manually
print("Hello " + name + "! Your score is " + str(score) + ".")
# Hello Riya! Your score is 95.
# Works, but ugly. Forget str() and it crashes.

Python has three solutions. The best is f-strings — introduced in Python 3.6 and now the standard.

Method 1 — f-strings (Best, Use Always)

Put the letter f before the opening quote. Then write any variable or expression inside curly braces {} — Python fills it in automatically:

python
name  = "Riya"
score = 95
city  = "Pune"

# f before the quote, variables inside {}
print(f"Hello {name}! Your score is {score}.")
# Hello Riya! Your score is 95.

print(f"{name} lives in {city} and scored {score}/100.")
# Riya lives in Pune and scored 95/100.

Expressions Inside f-strings

The real power: you can write any Python expression inside the curly braces — maths, method calls, conditions — anything:

python
price    = 250
quantity = 3
name     = "  riya  "
marks    = 72

# Maths inside {}
print(f"Total: Rs.{price * quantity}")      # Total: Rs.750

# Method call inside {}
print(f"Name: {name.strip().title()}")        # Name: Riya

# Condition inside {}
print(f"Result: {'Pass' if marks >= 35 else 'Fail'}")
# Result: Pass

Formatting Numbers in f-strings

Add a colon : inside the braces to control how numbers are displayed:

python
pi       = 3.14159265
amount   = 1234567.89
progress = 0.754

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

# , = thousands separator
print(f"Amount: Rs.{amount:,.2f}") # Amount: Rs.1,234,567.89

# % = percentage format
print(f"Done: {progress:.1%}")     # Done: 75.4%

# width = pad to fixed width (useful for alignment)
print(f"{'Name':12} Score")         # Name         Score
print(f"{'Riya':12} 95")            # Riya         95
print(f"{'Arjun':12} 88")           # Arjun        88

Method 2 — .format() (Older Style)

You will see this in older code. Uses {} as placeholders filled by .format():

python
name  = "Arjun"
score = 88

# Positional — filled left to right
print("Hello {}! Score: {}".format(name, score))
# Hello Arjun! Score: 88

# Named — clearer for complex strings
print("Hello {n}! Score: {s}".format(n=name, s=score))
# Hello Arjun! Score: 88
Which to Use?

Always use f-strings for new code — faster, cleaner, easier to read. Use .format() only when working with template strings stored in variables. The old %s style exists but avoid it in new code completely.

Real Example — Formatted Report Card

python
name    = "Kavya Sharma"
maths   = 92
science = 88
english = 79
total   = maths + science + english
avg     = total / 3

print(f"{'='*34}")
print(f"  REPORT — {name}")
print(f"{'='*34}")
print(f"  {'Maths':10}: {maths}/100")
print(f"  {'Science':10}: {science}/100")
print(f"  {'English':10}: {english}/100")
print(f"  {'-'*30}")
print(f"  {'Total':10}: {total}/300")
print(f"  {'Average':10}: {avg:.1f}%")
output
==================================
  REPORT — Kavya Sharma
==================================
  Maths     : 92/100
  Science   : 88/100
  English   : 79/100
  ------------------------------
  Total     : 259/300
  Average   : 86.3%

"f-strings make your code feel alive. The string reads like a sentence, the data flows in naturally. This is Python at its most elegant."

— ShurAI

🧠 Quiz — Question 1

How do you create an f-string in Python?

🧠 Quiz — Question 2

What does f"Pi = {3.14159:.2f}" output?

🧠 Quiz — Question 3

Given name="Raj" and age=20, which line prints Raj is 20 years old?

🧠 Quiz — Question 4

Can you put Python expressions (like maths) inside f-string curly braces?