Home › Learn › Python › Strings in depth

Formatting numbers

Lesson 27 of 40. Control decimals, thousands separators, and padding in f-strings.

Inside an f-string, a colon after the expression starts a format spec. {x:.2f} shows two decimal places, {x:,} inserts thousands separators, {x:,.2f} does both, {n:03d} pads a whole number with zeros to three digits, {r:.1%} multiplies by 100 and adds a percent sign, and {s:>8} right-aligns text in eight characters (< left, ^ center).

Formatting is for showing numbers; do the arithmetic on the real values and format at the last moment.

total = 1234.5
print(f"{total:,.2f}")   # 1,234.50
print(f"{7:03d}")        # 007
print(f"{0.4567:.1%}")   # 45.7%

Your task

Write money(amount) returning a dollar sign followed by the amount with thousands separators and two decimals ("$1,234.50"), pad(n) returning the number zero-padded to three digits ("007"), and percent(ratio) returning the ratio as a percentage with one decimal (0.45 becomes "45.0%").

Hint 1

f"${amount:,.2f}"

Hint 2

f"{n:03d}" and f"{ratio:.1%}"

Show the solution
def money(amount):
    return f"${amount:,.2f}"


def pad(n):
    return f"{n:03d}"


def percent(ratio):
    return f"{ratio:.1%}"

    Runs CPython compiled to WebAssembly in this tab (12 MB download the first time, then cached); nothing is sent anywhere.