{"course":{"slug":"python-for-ai","title":"Python, from Zero, for AI","url":"https://addaly.com/learn/python-for-ai","level":"beginner","track":"build"},"lesson":{"slug":"formatting-output","title":"Building the output a person will read","url":"https://addaly.com/learn/python-for-ai/formatting-output","position":7,"of":89,"minutes":7,"answer":"An f-string builds a string at the moment it runs, and the part after the colon controls only how the value is displayed, never the value itself.","keyIdea":"An f-string builds a string at the moment it runs, and the part after the colon controls only how the value is displayed, never the value itself."},"body":{"format":"markdown","text":"## f-strings, and why the plus sign fails\n\nYou want to print a sentence with a value in it. The obvious attempt:\n\n```python\nname = \"Asha\"\nowed = 1250\nprint(\"Hello \" + name + \", you owe \" + owed)\n```\n\n```\nTypeError: can only concatenate str (not \"int\") to str\n```\n\n`+` between two strings joins them; between a string and an int it has no defined meaning, so Python refuses rather than guessing. You could wrap it in `str(owed)`, and people did for years. The modern way is an **f-string**: put an `f` before the opening quote and put expressions in braces.\n\n```python\nprint(f\"Hello {name}, you owe {owed}\")\n```\n\nAnything can go inside the braces: a variable, arithmetic, a method call, an index:\n\n```python\nprint(f\"{name.upper()} owes {owed * 1.18:.2f} after tax\")\n```\n\nThe part after the colon is a **format specification**, and it is where most of the value is.\n\n## The format specifications worth memorising\n\n```python\nvalue = 1234567.8915\n\nf\"{value:.2f}\"  # '1234567.89'   two decimal places\nf\"{value:,.2f}\"  # '1,234,567.89' thousands separators\nf\"{0.0734:.1%}\"  # '7.3%'         as a percentage\nf\"{42:05d}\"  # '00042'        zero-padded to width 5\n# '     total'   right-aligned in 10 columns\nf\"{'total':>10}\"\nf\"{'total':<10}\"  # 'total     '   left-aligned\n# '  total   '   centred (the odd space goes right)\nf\"{'total':^10}\"\nf\"{255:x}\"  # 'ff'           hexadecimal\n```\n\nAlignment is what turns a wall of numbers into something readable in a terminal:\n\n```python\nfor item, cost in [(\"rice\", 340), (\"dal\", 1250), (\"oil\", 92)]:\n    print(f\"{item:<10}{cost:>8,}\")\n```\n\n```\nrice           340\ndal          1,250\noil             92\n```\n\n## The debugging form almost nobody knows\n\nPut `=` at the end of the expression:\n\n```python\n>>> count = 7\n>>> print(f\"{count = }\")\ncount = 7\n>>> print(f\"{count * 2 = }\")\ncount * 2 = 14\n```\n\nIt prints the expression *and* its value. When you are chasing a wrong number, this halves the typing and removes the classic mistake of labelling one variable with another variable's name. It needs Python 3.8 or newer.\n\n## Rounding for display is not rounding the value\n\n```python\nprice = 19.999\nprint(f\"{price:.2f}\")   # 20.00\nprint(price)            # 19.999\n```\n\nThe f-string produced a string. The variable is untouched. This is the right way round: keep full precision in the data, decide on presentation at the edge. Programs that call `round()` on the way in lose information they cannot get back.\n\n## The limitation: grouping is not local\n\n`{:,}` gives `1,234,567`. It does not give `12,34,567`, which is how that number is written across India: grouping in lakhs and crores after the first thousand. The comma specifier is hard-coded to groups of three.\n\nTo get local grouping you need the `locale` module and an `en_IN` locale actually installed on the machine, which on a stripped-down server or a phone it often is not:\n\n```python\nimport locale\nlocale.setlocale(locale.LC_ALL, \"en_IN.UTF-8\")   # may raise locale.Error\nlocale.format_string(\"%d\", 1234567, grouping=True)\n```\n\nIf that raises, and it will on many systems, write the grouping yourself with a small function, or use the `babel` package, which carries its own locale data and does not depend on the operating system. This is a real constraint, not a footnote: reports that show Indian currency in Western grouping look wrong to everyone reading them.\n\n## Older forms you will meet in other people's code\n\n```python\n\"Hello %s, you owe %d\" % (name, owed)      # the oldest, still in logging\n\"Hello {}, you owe {}\".format(name, owed)  # the middle era\n```\n\nBoth still work. Write f-strings in new code, and read the other two without panic. One exception: the `logging` module wants the `%s` form passed as separate arguments, for a reason covered when we get to logging.\n\n## `print` has two settings worth knowing\n\n```python\nprint(\"a\", \"b\", \"c\")                  # a b c\nprint(\"a\", \"b\", sep=\"\")               # ab\nprint(\"loading\", end=\"\")              # no newline afterwards\nprint(*[\"rice\", \"dal\", \"oil\"], sep=\"\\n\")\n```\n\n`sep` is what goes between the arguments, `end` is what goes after the last one, and it defaults to a newline. To update a progress line in a terminal, combine `end=\"\"` with `\"\\r\"` at the start of the text and `flush=True`. The carriage return moves back to the start of the line, and flushing makes the update visible immediately. For example, use `print(f\"\\r{pct}%\", end=\"\", flush=True)`. A triple-quoted string spans lines, which is often simpler than three separate `print` calls for a fixed block of text.\n\n## Two small traps\n\n- A literal brace needs doubling: `f\"{{literal}}\"` prints `{literal}`.\n- An f-string is built the moment the line runs. `f\"{total}\"` captures the value of `total` right then, not later.\n\n## Try this now\n\nPrint a three-column table of any five items you own, with the name left-aligned in 12 columns, a quantity right-aligned in 4, and a price with two decimals and thousands separators. Getting the columns to line up teaches the specifiers faster than reading them."},"check":{"question":"A report shows `f\"{total:.2f}\"` for every row and the printed column sums to 1 paisa less than the stored total. What is the correct account of this?","options":[{"text":"The f-string modified each stored value to two decimals, so the underlying data must be recovered from the source file.","correct":false,"tempting":"Assumes formatting mutates the variable, which is the mistake this lesson exists to prevent."},{"text":"Each printed row is the stored value rounded for display only; the sum of rounded numbers need not equal the rounded sum.","correct":true},{"text":"`.2f` truncates rather than rounds, so switching to `round(x, 2)` inside the braces will make the columns agree.","correct":false,"tempting":"Half-right about a difference between truncation and rounding, but `.2f` rounds, and rounding earlier would not make the two totals agree either."},{"text":"The values must be Decimal rather than float for a printed column to add up correctly.","correct":false,"tempting":"Reaches for the money-precision rule, which is real but does not remove the gap between a sum of rounded values and a rounded sum."}]},"prev":{"slug":"strings-and-input","title":"Strings, and why input() always hands you text","url":"https://addaly.com/learn/python-for-ai/strings-and-input"},"next":{"slug":"booleans-and-truth","title":"True, False, and what Python counts as nothing","url":"https://addaly.com/learn/python-for-ai/booleans-and-truth"},"authorship":"Founder and series editor: Dr Mustafa Mun. Written by AI models to a written standard. Source and assessment review continues. Academic review invited.","review":{"status":"Draft, open for academic review"},"cite":"Addaly (2026) 'Building the output a person will read', in Python, from Zero, for AI. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/python-for-ai/formatting-output (Accessed: 21 November 2026).","licence":{"name":"CC BY-NC-SA 4.0","url":"https://creativecommons.org/licenses/by-nc-sa/4.0/"},"reader":{"schema":1,"title":"Building the output a person will read","courseTitle":"Python, from Zero, for AI","module":{"index":1,"slug":"getting-python-running","title":"Getting Python running, and your first working code"},"answer":null,"keyIdea":"An f-string builds a string at the moment it runs, and the part after the colon controls only how the value is displayed, never the value itself.","hero":{"kind":"plate","image":null,"alt":null,"caption":null},"blocks":[{"t":"h2","id":"f-strings-and-why-the-plus-sign-fails","runs":[{"text":"f-strings, and why the plus sign fails"}]},{"t":"p","runs":[{"text":"You want to print a sentence with a value in it. The obvious attempt:"}]},{"t":"code","lang":"python","label":"Python","text":"name = \"Asha\"\nowed = 1250\nprint(\"Hello \" + name + \", you owe \" + owed)"},{"t":"code","lang":"","label":"Text","text":"TypeError: can only concatenate str (not \"int\") to str"},{"t":"p","runs":[{"text":"+","code":true},{"text":" between two strings joins them; between a string and an int it has no defined meaning, so Python refuses rather than guessing. You could wrap it in "},{"text":"str(owed)","code":true},{"text":", and people did for years. The modern way is an "},{"text":"f-string","b":true},{"text":": put an "},{"text":"f","code":true},{"text":" before the opening quote and put expressions in braces."}]},{"t":"code","lang":"python","label":"Python","text":"print(f\"Hello {name}, you owe {owed}\")"},{"t":"p","runs":[{"text":"Anything can go inside the braces: a variable, arithmetic, a method call, an index:"}]},{"t":"code","lang":"python","label":"Python","text":"print(f\"{name.upper()} owes {owed * 1.18:.2f} after tax\")"},{"t":"p","runs":[{"text":"The part after the colon is a "},{"text":"format specification","b":true},{"text":", and it is where most of the value is."}]},{"t":"h2","id":"the-format-specifications-worth-memorising","runs":[{"text":"The format specifications worth memorising"}]},{"t":"code","lang":"python","label":"Python","text":"value = 1234567.8915\n\nf\"{value:.2f}\"  # '1234567.89'   two decimal places\nf\"{value:,.2f}\"  # '1,234,567.89' thousands separators\nf\"{0.0734:.1%}\"  # '7.3%'         as a percentage\nf\"{42:05d}\"  # '00042'        zero-padded to width 5\n# '     total'   right-aligned in 10 columns\nf\"{'total':>10}\"\nf\"{'total':<10}\"  # 'total     '   left-aligned\n# '  total   '   centred (the odd space goes right)\nf\"{'total':^10}\"\nf\"{255:x}\"  # 'ff'           hexadecimal"},{"t":"p","runs":[{"text":"Alignment is what turns a wall of numbers into something readable in a terminal:"}]},{"t":"code","lang":"python","label":"Python","text":"for item, cost in [(\"rice\", 340), (\"dal\", 1250), (\"oil\", 92)]:\n    print(f\"{item:<10}{cost:>8,}\")"},{"t":"code","lang":"","label":"Text","text":"rice           340\ndal          1,250\noil             92"},{"t":"h2","id":"the-debugging-form-almost-nobody-knows","runs":[{"text":"The debugging form almost nobody knows"}]},{"t":"p","runs":[{"text":"Put "},{"text":"=","code":true},{"text":" at the end of the expression:"}]},{"t":"code","lang":"python","label":"Python","text":">>> count = 7\n>>> print(f\"{count = }\")\ncount = 7\n>>> print(f\"{count * 2 = }\")\ncount * 2 = 14"},{"t":"p","runs":[{"text":"It prints the expression "},{"text":"and","i":true},{"text":" its value. When you are chasing a wrong number, this halves the typing and removes the classic mistake of labelling one variable with another variable’s name. It needs Python 3.8 or newer."}]},{"t":"h2","id":"rounding-for-display-is-not-rounding-the-value","runs":[{"text":"Rounding for display is not rounding the value"}]},{"t":"code","lang":"python","label":"Python","text":"price = 19.999\nprint(f\"{price:.2f}\")   # 20.00\nprint(price)            # 19.999"},{"t":"p","runs":[{"text":"The f-string produced a string. The variable is untouched. This is the right way round: keep full precision in the data, decide on presentation at the edge. Programs that call "},{"text":"round()","code":true},{"text":" on the way in lose information they cannot get back."}]},{"t":"h2","id":"the-limitation-grouping-is-not-local","runs":[{"text":"The limitation: grouping is not local"}],"role":"limit"},{"t":"p","runs":[{"text":"{:,}","code":true},{"text":" gives "},{"text":"1,234,567","code":true},{"text":". It does not give "},{"text":"12,34,567","code":true},{"text":", which is how that number is written across India: grouping in lakhs and crores after the first thousand. The comma specifier is hard-coded to groups of three."}]},{"t":"p","runs":[{"text":"To get local grouping you need the "},{"text":"locale","code":true},{"text":" module and an "},{"text":"en_IN","code":true},{"text":" locale actually installed on the machine, which on a stripped-down server or a phone it often is not:"}]},{"t":"code","lang":"python","label":"Python","text":"import locale\nlocale.setlocale(locale.LC_ALL, \"en_IN.UTF-8\")   # may raise locale.Error\nlocale.format_string(\"%d\", 1234567, grouping=True)"},{"t":"p","runs":[{"text":"If that raises, and it will on many systems, write the grouping yourself with a small function, or use the "},{"text":"babel","code":true},{"text":" package, which carries its own locale data and does not depend on the operating system. This is a real constraint, not a footnote: reports that show Indian currency in Western grouping look wrong to everyone reading them."}]},{"t":"h2","id":"older-forms-you-will-meet-in-other-people-s-code","runs":[{"text":"Older forms you will meet in other people’s code"}]},{"t":"code","lang":"python","label":"Python","text":"\"Hello %s, you owe %d\" % (name, owed)      # the oldest, still in logging\n\"Hello {}, you owe {}\".format(name, owed)  # the middle era"},{"t":"p","runs":[{"text":"Both still work. Write f-strings in new code, and read the other two without panic. One exception: the "},{"text":"logging","code":true},{"text":" module wants the "},{"text":"%s","code":true},{"text":" form passed as separate arguments, for a reason covered when we get to logging."}]},{"t":"h2","id":"print-has-two-settings-worth-knowing","runs":[{"text":"print","code":true},{"text":" has two settings worth knowing"}]},{"t":"code","lang":"python","label":"Python","text":"print(\"a\", \"b\", \"c\")                  # a b c\nprint(\"a\", \"b\", sep=\"\")               # ab\nprint(\"loading\", end=\"\")              # no newline afterwards\nprint(*[\"rice\", \"dal\", \"oil\"], sep=\"\\n\")"},{"t":"p","runs":[{"text":"sep","code":true},{"text":" is what goes between the arguments, "},{"text":"end","code":true},{"text":" is what goes after the last one, and it defaults to a newline. To update a progress line in a terminal, combine "},{"text":"end=\"\"","code":true},{"text":" with "},{"text":"\"\\r\"","code":true},{"text":" at the start of the text and "},{"text":"flush=True","code":true},{"text":". The carriage return moves back to the start of the line, and flushing makes the update visible immediately. For example, use "},{"text":"print(f\"\\r{pct}%\", end=\"\", flush=True)","code":true},{"text":". A triple-quoted string spans lines, which is often simpler than three separate "},{"text":"print","code":true},{"text":" calls for a fixed block of text."}]},{"t":"h2","id":"two-small-traps","runs":[{"text":"Two small traps"}]},{"t":"ul","items":[[{"text":"A literal brace needs doubling: "},{"text":"f\"{{literal}}\"","code":true},{"text":" prints "},{"text":"{literal}","code":true},{"text":"."}],[{"text":"An f-string is built the moment the line runs. "},{"text":"f\"{total}\"","code":true},{"text":" captures the value of "},{"text":"total","code":true},{"text":" right then, not later."}]]},{"t":"h2","id":"try-this-now","runs":[{"text":"Try this now"}],"role":"try"},{"t":"p","runs":[{"text":"Print a three-column table of any five items you own, with the name left-aligned in 12 columns, a quantity right-aligned in 4, and a price with two decimals and thousands separators. Getting the columns to line up teaches the specifiers faster than reading them."}]}],"check":{"question":[{"text":"A report shows "},{"text":"f\"{total:.2f}\"","code":true},{"text":" for every row and the printed column sums to 1 paisa less than the stored total. What is the correct account of this?"}],"options":[{"text":[{"text":"The f-string modified each stored value to two decimals, so the underlying data must be recovered from the source file."}],"correct":false,"tempting":[{"text":"Assumes formatting mutates the variable, which is the mistake this lesson exists to prevent."}]},{"text":[{"text":"Each printed row is the stored value rounded for display only; the sum of rounded numbers need not equal the rounded sum."}],"correct":true,"tempting":null},{"text":[{"text":".2f","code":true},{"text":" truncates rather than rounds, so switching to "},{"text":"round(x, 2)","code":true},{"text":" inside the braces will make the columns agree."}],"correct":false,"tempting":[{"text":"Half-right about a difference between truncation and rounding, but "},{"text":".2f","code":true},{"text":" rounds, and rounding earlier would not make the two totals agree either."}]},{"text":[{"text":"The values must be Decimal rather than float for a printed column to add up correctly."}],"correct":false,"tempting":[{"text":"Reaches for the money-precision rule, which is real but does not remove the gap between a sum of rounded values and a rounded sum."}]}],"order":[0,2,3,1],"why":null},"prev":{"slug":"strings-and-input","title":"Strings, and why input() always hands you text","minutes":6},"next":{"slug":"booleans-and-truth","title":"True, False, and what Python counts as nothing","minutes":7}}}