Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Python string formatting: format text without building SQL syntax

Last updated: 30 Sept 20264 min read
tutorial
BeginnerBy AITrove Editorial

An f-string evaluates expressions and formats their values into a new string.

Download Python source kit

Operation contract

The receipt display uses integer minor units to format a major-unit and fractional part without converting through a float. The identifier and label are display text. Format alignment and decimal width are presentation rules; they do not validate a numeric range or make a displayed receipt authoritative.

Failure and ownership boundary

Putting caller text in an f-string does not escape it for HTML, SQL or a shell. Each sink needs its own binding or escaping policy. The fixture prints ordinary text only. Python sqlite3 transactions: bind values and roll back failed batches and Python JSON validation: reject duplicate members and non-integer amounts avoid treating a formatted string as a data contract.

Working program

python
receipt_id = 41
amount_minor = 1275
major, minor = divmod(amount_minor, 100)
print(f"R{receipt_id:04d} | INR {major}.{minor:02d}")

Output

Output
R0041 | INR 12.75

Costs and limits

Formatting allocates a string proportional to output length. A fixed display here is bounded; very large widths or numbers supplied by callers can add allocation cost.

Common Mistakes

  • Formatting is not HTML or SQL escaping.
  • Keep money units explicit.

Connected lessons

Python Decimal money: parse decimal text and choose rounding explicitly, Python sqlite3 transactions: bind values and roll back failed batches, Python JSON validation: reject duplicate members and non-integer amounts.

python
string-formatting
Storage details