Ravindra BagaleCourses & study guides मराठी Track your progress

Python Strings Tutorial: Slicing, f-strings and String Methods with Examples

P3.4 Python f-strings: Format Numbers, Money and Percentages

Why. Reports must look neat: two decimals for money, commas for thousands, a % sign for rates. f-strings do this in one line.

What. An f-string starts with f before the quote. Put variables inside {}. After a colon you can add a format.

  • {x:.2f} — 2 decimals
  • {x:,} — commas for thousands
  • {x:,.2f} — both
  • {x:.1%} — percentage with 1 decimal

How.

Write a formatted message

  1. Start the text with f".
  2. Write normal text.
  3. Put each variable in {}.
  4. Add a format after : if needed.

Worked example A — A simple f-string.

Step 1 — What we do. We greet a customer in Sydney.

Step 2 — Type and run this code.

name = "Liam"
orders = 4
print(f"Hi {name}, you have {orders} orders.")

Step 3 — Output you should see.

Hi Liam, you have 4 orders.

Step 4 — What it means. Values are placed into the text directly. No + and no str() needed.

Worked example B — Money with commas and decimals.

Step 1 — What we do. A Paris store sold goods worth 1234567.891 euros.

Step 2 — Type and run this code.

sales = 1234567.891
print(f"Sales: €{sales:,.2f}")

Step 3 — Output you should see.

Sales: €1,234,567.89

Step 4 — What it means. ,.2f adds commas and keeps 2 decimals: €1,234,567.89.

Worked example C — Percentages.

Step 1 — What we do. A hospital in Leeds discharged 45 of 60 patients this week.

Step 2 — Type and run this code.

rate = 45 / 60
print(f"Discharge rate: {rate:.1%}")

Step 3 — Output you should see.

Discharge rate: 75.0%

Step 4 — What it means. .1% multiplies by 100 and adds %, with 1 decimal: 75.0%.

Worked example D — Indian lakh style (simple helper).

Step 1 — What we do. Python commas use the international style. For ₹1,25,450 style we write a tiny helper.

Step 2 — Type and run this code.

def inr(n):
    s = str(int(n))
    if len(s) <= 3:
        return "₹" + s
    last3 = s[-3:]
    rest = s[:-3]
    groups = []
    while len(rest) > 2:
        groups.insert(0, rest[-2:])
        rest = rest[:-2]
    if rest:
        groups.insert(0, rest)
    return "₹" + ",".join(groups) + "," + last3
print(inr(125450))
print(inr(12345678))

Step 3 — Output you should see.

₹1,25,450
₹1,23,45,678

Step 4 — What it means. The helper groups the digits as 1,25,450 and 1,23,45,678. You will learn functions properly in the functions chapter; for now just see that text tools can build any format.

Ravindra Bagale's Tip

Use f-strings for every printed result. They are short, fast and easy to read.