Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

Python  Module 2 – Values, variables, numbers and strings

f-strings and the format mini-language

Format numbers, text and dates with Python f-strings and format specifications (width, alignment, precision, grouping), debug with =, and read % and format().

  • Beginner
  • 20 minutes
  • Examples run with Python 3.14.8 and Pyodide 314.0.7
  • By MySmartCoPilot
Free lesson, Pro answers: 20 minutes
Free: the whole lesson. With a pass: the model answers to its 2 interview questions.

What you will learn

  • Write f-strings that put the values of expressions into text
  • Format numbers, dates and text with a format specification
  • Use the = specifier and the !r conversion to debug values
  • Read older % and str.format() code and choose the style for new code

Before you start

Programs constantly turn values into text: a total on a receipt, a percentage in a report, a date on a ticket, a variable’s value while you hunt a bug. An f-string: A string literal with f before its opening quote, such as f"{price:.2f}". The expressions in its braces are evaluated when the line runs, and their values are put into the text. does that in one readable line, and the format specification: The code after the colon in a replacement field, such as >12,.2f, that sets fill and alignment, sign, width, grouping, precision and type. format(value, spec) applies one on its own. after a colon inside it controls the details: how wide, how many decimals, which separator, which alignment.

The receipt in this lesson writes its total, the float 10710.0, as 10,710.00 with the specification >12,.2f: right-aligned in 12 characters, with a comma and two decimals. You will build lines like it, format dates, show values exactly as they are while you debug, and read the two older styles that a lot of existing code still uses.

An f-string puts values into text when the line runs

Put f (or F) before the opening quote, and write expressions inside curly braces. Python evaluates each one when the line runs and puts its value into the text:

Expressions inside braces Python · first_fstrings.py
item = "masala dosa"
price = 85
quantity = 3

# Expressions inside the braces run when the line runs, and their values are put in the text.
print(f"{quantity} × {item} cost {price * quantity}")
print(f"{item.title()} has {len(item)} characters")

# Without the f, braces are ordinary characters.
print("{quantity} × {item}")

# Doubled braces print one brace.
print(f"{{quantity}} is replaced by {quantity}")

Output

3 × masala dosa cost 255
Masala Dosa has 11 characters
{quantity} × {item}
{quantity} is replaced by 3

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 first_fstrings.py

  • Anything that is an expression can go in the braces: a name, arithmetic, a method call such as item.title(). Unless a format specification (the next section) says otherwise, each value appears as str() would write it.
  • Forget the f and the braces are printed as typed, with no error to warn you. When you see {name} in your output, look for the missing f first.
  • To print a brace itself, double it: {{ and }}.

Version note

Since Python 3.12 (PEP 701), an expression inside an f-string may use the same kind of quotes as the f-string around it, as in f"{prices["tea"]}", may contain backslashes, and may run over several lines with comments. Python 3.11 and older reject the same line with a SyntaxError, so code that must run on them uses the other kind of quotes inside: f"{prices['tea']}".

“When the line runs” means once. Step through a program that changes a price after an f-string has used it, and watch the row of line:

Interactive · line by line An f-string runs once, where it is written Step through the program and compare the rows of price and line after each step.

Program · once_evaluated.py

price = 85
line = f"Price: {price}"
price = 90
print(line)
print(f"Price: {price}")

Variables

After line 5: price is 90; line is 'Price: 85'.price90line'Price: 85'
  • changed in this step

Printed so far

Price: 85
Price: 90

Every step was recorded from a run with Python 3.14.8 on macOS 26 arm64.

The drawing shows the variables when the program ends, and the program's 6 steps are listed below.

Line run 5
Next line end
Every step as text
  1. Start. No line has run yet, so there are no variables. Python starts with line 1.
  2. Line 1. price = 85 sets price to 85.
  3. Line 2. line = f"Price: {price}" sets line to 'Price: 85'. Key point The f-string runs now. Python reads price, 85, and line holds the finished text, an ordinary string.
  4. Line 3. price = 90 sets price to 90 (it was 85). price is 90 now, but line was built on the line before and does not change with it.
  5. Line 4. print(line) prints Price: 85.
  6. Line 5. print(f"Price: {price}") prints Price: 90. That was the last line, so the program ends. A new f-string reads price again, so this line shows 90.

line still holds 'Price: 85': the f-string built an ordinary string, and that string does not follow the variables it was made from. To show the new price, run an f-string again, as the last line does. A template that must wait for its values is a job for str.format(), one of the older styles at the end of this lesson.

Checkpoint

Check: Values in text with f-strings

  1. Question 1 of 2 What does this print?

    Read the code, then choose one answer.

    name = "Asha"
    print("Hello, {name}!")
    Show the answer: Question 1 of 2

    Answer: Hello, {name}!

    Only an f-string evaluates its braces. A missing f raises no error, so {name} in the output is the sign to look for it.

  2. Question 2 of 2 What does this print?

    Read the code, then choose one answer.

    count = 3
    msg = f"{count} items"
    count = 4
    print(msg)
    Show the answer: Question 2 of 2

    Answer: 3 items

    An f-string is evaluated once, where it is written. To use the new value, evaluate an f-string again after the change.

A format specification sets width, alignment and decimals

After the expression, a colon starts a format specification, a short code that says how the value should look. This receipt uses widths, alignment, decimals and commas:

A receipt in neat columns Python · receipt.py
order = [("Masala dosa", 2, 85), ("Filter coffee", 3, 30), ("Idli", 4, 12.5), ("Party thali", 40, 260)]

print(f"{'Item':<15}{'Qty':>5}{'Price':>9}{'Amount':>12}")
total = 0
# Each item is a tuple (name, quantity, price); the loop takes them one at a time.
for name, quantity, price in order:
    amount = quantity * price
    total += amount
    print(f"{name:<15}{quantity:>5}{price:>9.2f}{amount:>12,.2f}")
print(f"{'Total':<29}{total:>12,.2f}")
print(f"{' Thank you ':*^41}")

Output

Item             Qty    Price      Amount
Masala dosa        2    85.00      170.00
Filter coffee      3    30.00       90.00
Idli               4    12.50       50.00
Party thali       40   260.00   10,400.00
Total                           10,710.00
*************** Thank you ***************

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 receipt.py

The header line formats strings: {'Item':<15} pads “Item” with spaces to 15 characters, aligned left. The item lines format numbers: {price:>9.2f} writes the price with two decimals, right-aligned in 9 characters, and {amount:>12,.2f} adds a comma between every three digits. The last line centres a text with ^ and fills the spare room with *.

Every part of a specification is optional, but the parts that are present always come in this order:

  1. Fill and align, such as *>: < left, > right, ^ centre, and = puts the padding after the sign. Any fill character may come before the align character.
  2. Sign, such as +: + shows a sign on every number, and a space puts a space before positive numbers.
  3. z (Python 3.11 and newer): turns a negative zero after rounding, such as -0.00, into 0.00.
  4. #: the alternate form, which adds prefixes such as 0x for hexadecimal.
  5. 0: pads numbers with zeros after the sign.
  6. Width, such as 12: the minimum width in characters. Longer values are not cut.
  7. Grouping, such as ,: a comma (or _) between groups of three digits. With the types b, o, x and X, _ groups in fours instead.
  8. Precision, such as .2: the digits after the point for f, e and %, the significant digits for g, and the most characters kept for a string.
  9. Type, such as f: how to write the value, for example d, f, e, g, %, x or b.

Without an align character, strings line up on the left and numbers on the right. A width is only a minimum: a value longer than the width is printed in full, which keeps numbers correct but can push a column out of line.

Step through one value, 1234.5, formatted with a specification that gains one part on each pass, from .2f to *>+12,.2f, and watch the row of text:

Interactive · line by line One number, a specification that grows one part at a time Step through the loop. Each cell under specs is a specification; the row of text shows what format() made of 1234.5 with it.

Program · spec_parts.py

value = 1234.5
specs = [".2f", ",.2f", "+,.2f",
         "+12,.2f", "*>+12,.2f"]
for spec in specs:
    text = format(value, spec)
    print(f"{spec:>9}  {text!r}")

Variables

After line 4: value is 1234.5; specs is ['.2f', ',.2f', '+,.2f', '+12,.2f', '*>+12,.2f'] (the loop stopped at position 5); spec is '*>+12,.2f'; text is '***+1,234.50'.value1234.5specs'.2f'0',.2f'1'+,.2f'2'+12,.2f'3'*>+12,.2f'45endspec'*>+12,.2f'text'***+1,234.50'
  • just taken by the loop
  • changed in this step
  • passed by the loop
  • read next
  • where the loop stopped

Printed so far

      .2f  '1234.50'
     ,.2f  '1,234.50'
    +,.2f  '+1,234.50'
  +12,.2f  '   +1,234.50'
*>+12,.2f  '***+1,234.50'

Every step was recorded from a run with Python 3.14.8 on macOS 26 arm64.

The drawing shows the variables when the program ends, and the program's 19 steps are listed below.

Line run 4
Next line end
Loop pass 5
Every step as text
  1. Start. No line has run yet, so there are no variables. Python starts with line 1.
  2. Line 1. value = 1234.5 sets value to 1234.5.
  3. Line 2. specs = [".2f", ",.2f", "+,.2f", "+12,.2f", "*>+12,.2f"] makes specs a list of 5 items.
  4. Line 4. for spec in specs: takes the item at position 0 of specs: spec is '.2f'.
  5. Line 5. text = format(value, spec) sets text to '1234.50'. .2f alone: the type f with a precision of 2 writes two decimals.
  6. Line 6. print(f"{spec:>9} {text!r}") prints .2f '1234.50'.
  7. Line 4. for spec in specs: takes the item at position 1 of specs: spec is ',.2f'.
  8. Line 5. text = format(value, spec) sets text to '1,234.50' (it was '1234.50'). The grouping option , adds a comma between every three digits of the whole part.
  9. Line 6. print(f"{spec:>9} {text!r}") prints ,.2f '1,234.50'.
  10. Line 4. for spec in specs: takes the item at position 2 of specs: spec is '+,.2f'.
  11. Line 5. text = format(value, spec) sets text to '+1,234.50' (it was '1,234.50'). + puts a sign before the number, positive or not.
  12. Line 6. print(f"{spec:>9} {text!r}") prints +,.2f '+1,234.50'.
  13. Line 4. for spec in specs: takes the item at position 3 of specs: spec is '+12,.2f'.
  14. Line 5. text = format(value, spec) sets text to ' +1,234.50' (it was '+1,234.50'). The width 12 makes the text at least 12 characters long. A number lines up on the right, so the three spaces go on the left.
  15. Line 6. print(f"{spec:>9} {text!r}") prints +12,.2f ' +1,234.50'.
  16. Line 4. for spec in specs: takes the item at position 4 of specs: spec is '*>+12,.2f'.
  17. Line 5. text = format(value, spec) sets text to '***+1,234.50' (it was ' +1,234.50'). Key point *> fills those three places with stars instead of spaces. Every part of *>+12,.2f is now in the text.
  18. Line 6. print(f"{spec:>9} {text!r}") prints *>+12,.2f '***+1,234.50'.
  19. Line 4. for spec in specs: finds no item at position 5 of specs (it has 5 items), so the loop ends. That was the last line, so the program ends.

Each part changed one thing: the comma grouped the digits, + added a sign, the width 12 padded the text on the left with three spaces, and *> filled those three places with stars. Read *>+12,.2f from left to right and you meet the parts in the order of the list above.

Key idea

A specification is read part by part, fill and align, sign, width, grouping, precision and type, and every part you leave out keeps its default.

Checkpoint

Check: Width, alignment and fill

  1. Question 1 of 2 What does this print?

    Read the code, then choose one answer.

    print(f"[{'tea':>6}]")
    Show the answer: Question 1 of 2

    Answer: [ tea]

    A width sets the minimum number of characters and the align character says where the padding goes: < after the text, > before it, ^ on both sides.

  2. Question 2 of 2 x is 3.14159. Which f-string gives exactly "3.14 ", 3.14 and then four spaces?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: f"{x:<8.2f}"

    The parts of a specification keep their order: align, width, precision, type. <8.2f puts the number on the left of eight characters with two decimals.

The type letter decides how a number is written

format(value, spec) applies one specification and returns the text, exactly as an f-string does after its colon. This program runs a list of specifications through it:

One value, many specifications Python · number_specs.py
# format(value, spec) applies one format specification; an f-string does the same after the colon.
examples = [
    (1234567.891, ".2f"),
    (1234567.891, ",.2f"),
    (1234567.891, "_.0f"),
    (1234567.891, ".3e"),
    (1234567.891, ".3g"),
    (0.256, ".1%"),
    (42, "+d"),
    (42, "06d"),
    (255, "x"),
    (255, "#X"),
    (5, "08b"),
    (-0.004, ".2f"),
    (-0.004, "z.2f"),
]
for value, spec in examples:
    print(f"{value!r:>11} {spec!r:7} → {format(value, spec)}")

Output

1234567.891 '.2f'   → 1234567.89
1234567.891 ',.2f'  → 1,234,567.89
1234567.891 '_.0f'  → 1_234_568
1234567.891 '.3e'   → 1.235e+06
1234567.891 '.3g'   → 1.23e+06
      0.256 '.1%'   → 25.6%
         42 '+d'    → +42
         42 '06d'   → 000042
        255 'x'     → ff
        255 '#X'    → 0XFF
          5 '08b'   → 00000101
     -0.004 '.2f'   → -0.00
     -0.004 'z.2f'  → 0.00

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 number_specs.py

  • f gives a fixed number of decimals and e scientific notation. g picks one of the two and drops zeros at the end; with .3g it keeps three significant digits.
  • % multiplies by 100 and adds a percent sign, so store fractions (0.256) rather than percentages.
  • d is a whole number, x and X hexadecimal, b binary and o octal; # adds the prefix (0X), and 08b pads with zeros to eight places.
  • Rounding to a precision follows the same rules as round(), on the binary value a float really holds, so a few decimal numbers round the “wrong” way; the floating-point lesson explains why. For money, keep whole paise or cents in an integer, or use decimal.Decimal.
  • -0.004 rounds to -0.00, which looks odd on a report; the z option writes 0.00 instead.

Version note

New in Python 3.14: the grouping option can also follow the precision, to group the digits after the decimal point. Python 3.13 and older reject these specifications with a ValueError.

Grouping digits after the point Python · fraction_grouping.py
value = 1234567.891234

print(f"{value:,f}")
print(f"{value:,._f}")
print(f"{value:_._f}")
print(f"{0.000123456789:.10_f}")

Output

1,234,567.891234
1,234,567.891_234
1_234_567.891_234
0.000_123_456_8

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 fraction_grouping.py

Lakh and crore

The , option always groups in threes, the international way: 1,234,567. Indian writing groups the last three digits and then pairs, so one lakh is 1,00,000 and the same number is 12,34,567. No option of a format specification does that on its own. The n type groups digits the way the current locale does, so an Indian locale can give that grouping, but a program must first choose one with locale.setlocale(), and the locales differ from one system to another (in the browser runner, n adds no separators at all). Programs that need Indian grouping therefore usually do it themselves, as this lesson’s exercise does.

Lakh Crore Converter (to Million, Billion) Check any amount in both groupings, and in lakh, crore, million and billion, to test your own function.

A common mistake: the wrong type code

Each type code belongs to some kinds of value. d is for integers, and a float does not convert itself silently:

d is for whole numbers Python · mistakes.py
price = 49.75

# A float with no decimals shown: the f type with precision 0 rounds it.
print(f"{price:.0f}")

# The d type is for integers only, so this line stops the program.
print(f"{price:d}")

Output (exit status 1)

50

Printed as an error (standard error)

Traceback (most recent call last):
  File "mistakes.py", line 7, in <module>
    print(f"{price:d}")
            ^^^^^^^^^
ValueError: Unknown format code 'd' for object of type 'float'

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 mistakes.py

{price:.0f} is the way to show a float without decimals (it rounds). For text, only a fill with the alignments <, > and ^, a width, a precision (which cuts the text short) and the type s make sense: {name:,} fails because commas mean nothing for a string.

Checkpoint

Check: Type letters for numbers

  1. Question 1 of 2 What does this print?

    Read the code, then choose one answer.

    print(f"{0.256:.1%}")
    Show the answer: Question 1 of 2

    Answer: 25.6%

    Store fractions and let % turn them into percentages: 0.256 with .1% gives 25.6%.

  2. Question 2 of 2 What happens with f"{49.75:d}"?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: It raises ValueError, because d is for integers

    Each type letter belongs to some kinds of value. For a float without decimals write {price:.0f}, which rounds.

Dates take strftime codes after the colon

Dates and times have their own specification language: after the colon come the strftime code: A code such as %d, %B or %H that stands for one part of a date or a time. It goes after the colon when an f-string formats a datetime, or into strftime(). of the datetime module, such as %d for the day, %B for the month’s name and %H:%M for a 24-hour time:

Formatting a date and time Python · dates.py
from datetime import datetime

departure = datetime(2030, 3, 14, 6, 5)

# Dates and times take strftime codes after the colon.
print(f"{departure:%d %B %Y, %H:%M}")
print(f"{departure:%a %d %b}")
print(f"{departure:%Y-%m-%d %H:%M}")
print(f"Boarding at {departure:%I:%M %p}")

Output

14 March 2030, 06:05
Thu 14 Mar
2030-03-14 06:05
Boarding at 06:05 AM

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 dates.py

%Y-%m-%d gives the international ISO 8601 order, which also sorts correctly as text. The names of days and months come from the current locale. Whatever the computer’s language, a Python program starts with the plain C locale, which uses English names, until it calls locale.setlocale().

The program uses these codes, each of which stands for one part of the date or time:

Code What it writes
%d, %m, %Y the day and the month as two digits, the year as four
%B, %b the month’s full or short name
%a the weekday’s short name
%H:%M the hour from 00 to 23, then the minutes
%I:%M %p the hour from 01 to 12, the minutes, then AM or PM

Press Edit and change %a in the second line to %A: the weekday is written in full, Thursday.

Checkpoint

Check: strftime codes for dates

  1. Question 1 of 2 Which code writes the month's full name, such as March?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: %B

    The capital and small letters of strftime codes mean different things: %B and %b are the month's names, %m its number, and %M the minutes.

  2. Question 2 of 2 What does this print?

    Read the code, then choose one answer.

    from datetime import datetime
    t = datetime(2030, 3, 14, 18, 30)
    print(f"{t:%I:%M %p}")
    Show the answer: Question 2 of 2

    Answer: 06:30 PM

    %I:%M %p is the 12-hour form of a time and %H:%M the 24-hour form; the names AM and PM come from the current locale, which is the plain C locale until a program changes it.

The equals specifier and !r show what a value really is

Add = after the expression and the f-string prints the expression’s text, an equals sign and the value. It is the quickest way to look at a few values while you hunt a bug:

The = specifier Python · debug_values.py
total = 1234.5
city = "Pune "

print(f"{total=}")
print(f"{total = :,.2f}")
print(f"{city=}")
print(f"{city!r} has {len(city)} characters")

Output

total=1234.5
total = 1,234.50
city='Pune '
'Pune ' has 5 characters

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 debug_values.py

  • The spaces you write around = are kept, so {total = } prints total = ….
  • A format specification can follow: {total = :,.2f}.
  • Without a specification, = shows the value with repr(), so a string appears in quotes and its trailing space becomes visible. The conversion: !r, !s or !a after the expression in an f-string's braces: the value is turned into text with repr(), str() or ascii() before it is formatted. f"{city!r}" shows a string in quotes. !r asks for repr() anywhere (and !s for str(), !a for ascii()). Use it whenever spaces, empty strings or the difference between "7" and 7 might matter.

Press Edit, remove the space at the end of "Pune " and run the program again: the quotes stay, and the length drops to 4. The trailing space was a character like any other, and only repr() made it visible.

Checkpoint

Check: = and !r for debugging

  1. Question 1 of 2 What does this print?

    Read the code, then choose one answer.

    name = "Ravi"
    print(f"{name=}")
    Show the answer: Question 1 of 2

    Answer: name='Ravi'

    {expr=} is meant for debugging: it shows what was evaluated and what came out, with quotes on strings so that spaces and empty strings are visible.

  2. Question 2 of 2 city may end with a stray space. Which f-string makes that space visible?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: f"{city!r}"

    !r and = show values the way they would be written in code. That is the quickest way to spot a stray space, an empty string, or "7" where 7 was expected.

Percent formatting and str.format() still appear in older code

f-strings arrived in Python 3.6, so older code, many libraries and a lot of answers online use the two styles that came before. They print the same result here:

Three ways to format the same line Python · old_styles.py
name = "Asha"
score = 0.8765

# printf-style formatting with %, the oldest style.
print("%s scored %.1f%%" % (name, score * 100))

# str.format(), with the same mini-language as f-strings after each colon.
print("{} scored {:.1%}".format(name, score))
print("{0} scored {1:.1%}. Well done, {0}!".format(name, score))
print("{who} scored {mark:.1%}".format(who=name, mark=score))

# The f-string that does the same.
print(f"{name} scored {score:.1%}")

Output

Asha scored 87.6%
Asha scored 87.6%
Asha scored 87.6%. Well done, Asha!
Asha scored 87.6%
Asha scored 87.6%

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 old_styles.py

  • printf-style formatting with % puts the values after the string: %s for any value as text, %d for an integer, %.1f for a float with one decimal, and %% for a percent sign. You will meet it in the logging module and in old code. The Python documentation lists its quirks: a single tuple or dictionary as the value is easy to get wrong.
  • str.format() uses braces like an f-string, with the values given as arguments: {} takes the next one, {0} a position (which may repeat) and {who} a keyword. After a colon it uses the same mini-language as f-strings. It is still useful when the template is data, such as a message read from a translation file, because an f-string must be written in the code. Use only templates you control: a field such as {0.__class__} reads an attribute of the value it is given.

The releases below put the styles in order, with the features the format language gained since. Walk through them to see which line of code needs which Python:

Timeline · 6 events in order How formatting text in Python grew Walk through the releases in order. Each added a way of formatting that the code you read may use.
  1. 3.0

    str.format() and the format mini-language

    PEP 3101 adds the format() method of strings, the built-in format() and the specification after a colon, the one f-strings use today.

  2. 3.6

    f-strings new syntax

    PEP 498 lets expressions sit in braces inside a string literal that has an f before it. They are evaluated when the line runs.

  3. 3.8

    The = specifier

    f"{total=}" writes the text of the expression, an equals sign and the value, the quickest way to look at values while you debug.

  4. 3.11

    The z option

    PEP 682 adds z to the specification, which turns a negative zero after rounding, such as -0.00, into 0.00.

  5. 3.12

    Any expression in the braces new syntax

    PEP 701 lets an expression reuse the f-string's own quotes, hold backslashes and run over several lines with comments.

  6. 3.14

    t-strings, and grouping after the point new syntax

    PEP 750 adds template strings, which let a library see each value before it is used, and a specification may now group the digits after the decimal point.

The timeline has 6 events, from 3.0 to 3.14.

For new code, write f-strings; keep str.format() for templates that are data, and % for the logging calls that expect it.

Security

Never paste user input into SQL, HTML or shell commands with an f-string or format(): input such as x'; DROP TABLE users; -- would become part of the command. Databases take parameters (? placeholders in sqlite3), html.escape() makes text safe to show in HTML (between tags or in a quoted attribute), subprocess.run() given a list of arguments starts a program without a shell, so no value is read as a command, and Python 3.14’s template strings (t-strings, PEP 750) let a library see each value before it is inserted. Later lessons cover each of them.

Checkpoint

Check: % and str.format()

  1. Question 1 of 2 This line comes from older code. What does it print?

    Read the code, then choose one answer.

    print("%s has %d" % ("Asha", 3))
    Show the answer: Question 1 of 2

    Answer: Asha has 3

    printf-style formatting puts the values after the string, in a tuple when there is more than one, and fills the placeholders from left to right.

  2. Question 2 of 2 What does this print?

    Read the code, then choose one answer.

    print("{who} {0}".format("hi", who="Asha"))
    Show the answer: Question 2 of 2

    Answer: Asha hi

    In str.format(), {0} names a position, {who} a keyword, and {} the next position. The template can be a string read from anywhere, which is what makes this style useful for templates that are data.

Practise: format rupees the Indian way

The , option groups only in threes, so this exercise asks you to write the Indian grouping yourself. It needs divmod() on whole paise, slices taken from the end of the digits and an f-string for the two decimals. Its sample tests run in your browser, with a first hint for when you are stuck:

Exercise · Medium · Python

Format rupees with Indian digit grouping

In India, large amounts group their digits in a different way from , in a format specification: the last three digits form a group, and every group before them has two digits. One lakh is 1,00,000 and one crore is 1,00,00,000.

Write format_inr(paise), which takes an amount of money as a whole number of paise (100 paise make one rupee) and returns it as rupees with that grouping and exactly two decimals:

  • format_inr(123456789) returns "₹12,34,567.89" and format_inr(100000) returns "₹1,000.00".
  • Small amounts keep a zero before the point: format_inr(99) returns "₹0.99" and format_inr(0) returns "₹0.00".
  • A negative amount has its minus sign before the rupee sign: format_inr(-150) returns "-₹1.50".

Work with whole numbers (divmod() splits the paise into rupees and the paise left over), not with floats, so that no paisa is lost to rounding. The sample tests import your function from rupees.py.

Starter code · rupees.py

def format_inr(paise):
    """Return an amount in paise as rupees with Indian digit grouping, such as '₹12,34,567.89'."""
    # Replace this line with your code.
    return ""
The sample tests · test_rupees.py
from rupees import format_inr


def test_small_amounts():
    """keeps a zero rupee before the point and two digits of paise"""
    assert format_inr(0) == "₹0.00"
    assert format_inr(5) == "₹0.05"
    assert format_inr(99) == "₹0.99"
    assert format_inr(100) == "₹1.00"


def test_thousands():
    """puts the first comma before the last three digits"""
    assert format_inr(99999) == "₹999.99"
    assert format_inr(100000) == "₹1,000.00"
    assert format_inr(9999999) == "₹99,999.99"


def test_lakh_and_crore():
    """groups the digits before the last three in pairs"""
    assert format_inr(10000000) == "₹1,00,000.00"
    assert format_inr(123456789) == "₹12,34,567.89"
    assert format_inr(1000000000) == "₹1,00,00,000.00"
    assert format_inr(98765432100) == "₹98,76,54,321.00"


def test_negative():
    """puts the minus sign before the rupee sign"""
    assert format_inr(-150) == "-₹1.50"
    assert format_inr(-123456789) == "-₹12,34,567.89"


def test_very_large():
    """keeps grouping in pairs beyond a crore, with no rounding"""
    assert format_inr(10**14 + 1) == "₹10,00,00,00,00,000.01"
    assert format_inr(123456789012345678) == "₹1,23,45,67,89,01,23,456.78"
A hint

rupees, rest = divmod(abs(paise), 100) gives the two parts, and f"{rest:02d}" writes the paise with two digits. For the grouping, turn the rupees into text with str(), split off the last three digits with digits[-3:], and then, while the part in front (digits[:-3]) is longer than two digits, keep taking two digits off its end with head[-2:] and head[:-2]. Collect the groups in a list and finish with ",".join(groups).

The sample tests run on this device, in your browser (Pyodide): nothing is sent to mysmartcopilot.com. The first run downloads Python (about 13.5 MB), which is kept for the next runs. A check in your browser is feedback for you, not proof that the code is right for every input.

Then try the lesson’s own questions. Each one checks a single idea, the session moves on to harder ones as you get them right, and every answer comes with its reason:

Practice that adapts to you

Practise this lesson

17 questions about 6 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.

  1. Question 1 of 17 What does debug_values.py print?

    What does this program print? Choose one answer.

    total = 1234.5
    city = "Pune "
    
    print(f"{total=}")
    print(f"{total = :,.2f}")
    print(f"{city=}")
    print(f"{city!r} has {len(city)} characters")
    Show the answer: Question 1 of 17

    Answer: it prints

    total=1234.5
    total = 1,234.50
    city='Pune '
    'Pune ' has 5 characters

    {total=} prints the expression, an equals sign and the value, and keeps the spaces written around =. Without a format specification the value is shown with repr(), so the string appears in quotes and its trailing space is visible; !r asks for repr() explicitly. The space counts as a character, so the length is 5.

  2. Question 2 of 17 What does this print?

    Read the code, then choose one answer.

    print(f"{'Menu':*^10}")
    Show the answer: Question 2 of 17

    Answer: ***Menu***

    * is the fill character, ^ centres the text and 10 is the width. "Menu" has 4 characters, so the 6 left over are split evenly, three on each side.

  3. Question 3 of 17 x is 3.14159. Which f-string gives exactly " 3.14", four spaces and then 3.14?

    Choose one answer.

    Show the answer: Question 3 of 17

    Answer: f"{x:8.2f}"

    Numbers are right-aligned by default, so a width of 8 with precision 2 pads 3.14 with four spaces on the left. < would align it left, a 0 before the width pads with zeros (00003.14), and the width must come before the precision, so .2f8 is not a valid specification.

  4. Question 4 of 17 This line comes from older code. What does it print?

    Read the code, then choose one answer.

    print("{0}-{1}-{0}".format("ping", "pong"))
    Show the answer: Question 4 of 17

    Answer: ping-pong-ping

    The numbers in the braces are positions in the arguments of format(), and a position can be used more than once, so {0} is "ping" both times.

  5. Question 5 of 17 Put these parts of a format specification in the order Python reads them.

    Give each item its position, from 1 (first).

    Show the answer: Question 5 of 17

    Answer:

    1. fill and align, such as *>
    2. sign, such as +
    3. width, such as 12
    4. grouping, such as a comma
    5. precision, such as .2
    6. type, such as f

    A specification such as *>+12,.2f is read from left to right: fill and align, then the sign, the width, the grouping, the precision and finally the type. Every part is optional, but those that are there keep this order.

  6. Question 6 of 17 When does Python evaluate the expressions inside an f-string?

    Choose one answer.

    Show the answer: Question 6 of 17

    Answer: When the line with the f-string runs

    An f-string is an expression. It is evaluated where it is written, once each time that line runs, like any other expression.

  7. Question 7 of 17 What does this print?

    Read the code, then choose one answer.

    print(f"{{x}} = {2 + 3}")
    Show the answer: Question 7 of 17

    Answer: {x} = 5

    To write a brace in an f-string, double it. Only single braces start a field.

  8. Question 8 of 17 A welcome message is read from a translation file, such as "Namaste, {name}!", and filled in later. Which tool fits?

    Choose one answer.

    Show the answer: Question 8 of 17

    Answer: str.format() with a named field, template.format(name=user)

    Use f-strings for text written in your code and str.format() for templates that arrive as data, and give it only templates you control.

  9. Question 9 of 17 Which type letter writes 255 as ff?

    Choose one answer.

    Show the answer: Question 9 of 17

    Answer: x

    x and X are hexadecimal, b binary and o octal; add # for the prefix, as in {255:#x}, which gives 0xff.

  10. Question 10 of 17 What does this print?

    Read the code, then choose one answer.

    print(f"{1234567:,}")
    Show the answer: Question 10 of 17

    Answer: 1,234,567

    , (or _) groups the digits of the whole part in threes. Indian grouping in lakh and crore needs your own code, as the exercise shows.

  11. Question 11 of 17 A report shows -0.00 for refunds so small that they round to zero. Which change fixes the display and leaves the numbers alone?

    Choose one answer.

    Show the answer: Question 11 of 17

    Answer: Add the z option, as in f"{amount:z.2f}"

    The z option (Python 3.11 and newer) exists for exactly this: a value that rounds to zero is written without a minus sign.

  12. Question 12 of 17 Which format makes dates sort correctly as text?

    Choose one answer.

    Show the answer: Question 12 of 17

    Answer: %Y-%m-%d

    %Y-%m-%d is the ISO 8601 order: year, month, day, each with a fixed number of digits. That is why it sorts correctly as plain text.

  13. Question 13 of 17 A program prints month names with %B. The computer it runs on is set to Hindi. Which names appear if the program never calls locale.setlocale()?

    Choose one answer.

    Show the answer: Question 13 of 17

    Answer: English names, from the plain C locale

    Names of months and days come from the current locale, and every Python program starts with the C locale until it calls locale.setlocale().

  14. Question 14 of 17 total is 42. What does f"{total=}" give?

    Choose one answer.

    Show the answer: Question 14 of 17

    Answer: total=42

    {expr=} writes expr= followed by the value's repr(), which for 42 is 42.

  15. Question 15 of 17 a = "7" and b = 7 print the same with print(a, b). Which f-string shows them differently?

    Choose one answer.

    Show the answer: Question 15 of 17

    Answer: f"{a!r} {b!r}"

    !r shows a value as code would write it, which separates a string of digits from a number. {a=} and {b=} would show the same difference.

  16. Question 16 of 17 In printf-style formatting, how do you write a percent sign in the result?

    Choose one answer.

    Show the answer: Question 16 of 17

    Answer: %%

    In the % style, %% writes one percent sign; in str.format() and f-strings, the % type adds it for you.

  17. Question 17 of 17 Why should str.format() only be given templates you control?

    Choose one answer.

    Show the answer: Question 17 of 17

    Answer: A field such as {0.__class__} reads attributes of the values it is given

    str.format() can follow attributes and items of its arguments, so a template written by someone else can make your program reveal data. Fill templates you wrote, or use a template system that limits what fields may do.

Interview questions

Fresher · What are f-strings, and why are they preferred to % formatting and str.format()?

An f-string is a string literal with an f before it, such as f"{name} scored {score:.1%}". The expressions in its braces are evaluated when the line runs, and each value is formatted by the specification after its colon, the same mini-language that format() and str.format() use. New code prefers them because each value sits where it appears in the text, which is easier to read and harder to get wrong than a % string whose tuple must line up with its placeholders, or a format() call with numbered fields. They also offer = for debugging. The older styles keep their uses: str.format() fills templates that are data, such as translated messages, because an f-string must be written in the code, and logging waits to apply its % formatting until a message is really written out.

Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.

  1. Fresher to mid

    An invoice prints each line with f"{amount:.2f}" and the total with f"{total:.2f}", where total adds the unrounded line amounts. Three items at 84.75 rupees plus 18 % GST each show 100.00, but the total shows 300.01. Explain both numbers and fix the invoice.

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page. First step and follow-ups

  2. Mid to senior

    A service calls logger.debug(f"order={order!r}") on every request. In production the level is INFO, so no debug line is ever written, yet profiling shows real time spent in these calls. Explain why, fix it, and say when an f-string in a log call is still fine.

    Model answer, Pro. First step and follow-ups

Key takeaways

  • f"…{expression}…" puts the value of each expression into the text when the line runs, once; without the f, braces are printed as typed.
  • After a colon, a format specification controls the text: fill and align, sign, z, #, 0, width, grouping, precision and type, always in that order.
  • ,.2f gives two decimals with commas, % a percentage, x and b hexadecimal and binary, and <, > and ^ align within a width; Python 3.14 can also group the digits after the point.
  • , always groups in threes; other conventions, such as the Indian grouping in pairs, need your own code.
  • Dates take strftime codes after the colon, and {value=} and !r show what a value really is while you debug.
  • % formatting and str.format() still appear in older code; format() uses the same mini-language as f-strings.

Terms in this lesson

conversion
!r, !s or !a after the expression in an f-string's braces: the value is turned into text with repr(), str() or ascii() before it is formatted. f"{city!r}" shows a string in quotes.
f-string
A string literal with f before its opening quote, such as f"{price:.2f}". The expressions in its braces are evaluated when the line runs, and their values are put into the text.
format specification
The code after the colon in a replacement field, such as >12,.2f, that sets fill and alignment, sign, width, grouping, precision and type. format(value, spec) applies one on its own.
strftime code
A code such as %d, %B or %H that stands for one part of a date or a time. It goes after the colon when an f-string formats a datetime, or into strftime().

References

Related tools

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.