Lesson 44 of 55
8 mins readPython Formatted Strings: string.format()
In Plain English
`string.format(fmt, ...)` formats strings using standard ANSI C `printf` directives: `%s` (strings), `%d` (integers), `%f` (floats), `%x` (hexadecimal), and `%q` (quoted strings).
Deep Dive: How It Works
%d / %i: Format decimal integers.
%s: Format any string or value.
%.2f: Format float to 2 decimal places.
%04d: Zero-pad an integer to 4 digits width.
%q: Formats string safely with quotes and escapes for code generation.
Core Rules to Remember

printf Compatibility: Standard specifiers for precision, padding, and type formatting.

Zero-Padding and Precision: `%02d` for dates and `%.2f` for currency amounts.
Live Interactive Example
Hit Run Code to see it liveFormatting Strings with string.format
Python 3.12
1
2
3
4
5
6
7
8
9
Output Console
Click "Run Code" to view the rendered output.
How it works: string.format aligned strings, zero-padded the ID, and rounded balance to 2 decimals.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Format Endpoint and Port
Declare `local host = "api.zen"` and `local port = 443`.
Format with `string.format("Endpoint: https://%s:%d", host, port)` and print it.
1
2
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.