In Python’s legacy % (printf-style) string formatting, %s is a format specifier that converts any Python object into a human-readable string by calling str(obj) under the hood and inserts it at that position—for example, "User: %s" % 42 evaluates to "User: 42"—whereas %r calls repr(obj), %d formats integers, and %f formats floating-point numbers.
Basic Example
name = "Amina"
score = 98.5
tags = ["python", "cli"]
# 1. `%s` converts ANY object via `str()` (strings, ints, floats, lists, custom objects):
msg = "Player %s scored %s points with tags %s" % (name, score, tags)
print(msg)
# Output: Player Amina scored 98.5 points with tags ['python', 'cli']
# 2. Named dictionary placeholders `%(key)s`:
template = "Host: %(host)s | Port: %(port)s"
print(template % {"host": "localhost", "port": 8080})
# Output: Host: localhost | Port: 8080
# 3. Recommended modern equivalents (f-strings in general code; `%s` stays standard in `logging`):
import logging
logging.warning("Failed login for user %s from %s", name, "10.0.0.5") # Lazy formatting
print(f"Player {name} scored {score} points") # f-string (Python 3.6+)
Key Details & Edge Cases
- Why
%sworks on integers, floats, and lists (unlike C’sprintf):- In C, passing an
intto%scauses undefined behavior or a segmentation fault. In Python,%sinvokesstr(arg)on whatever object you pass, so"%s" % 123and"%s" % [1, 2]succeed cleanly without raisingTypeError.
- In C, passing an
- Single-tuple trap (
TypeError: not all arguments converted during string formatting):- When formatting a single value with
%, passing atupledirectly—"%s" (10, 20)—is unpacked as two positional arguments for one%sslot, raisingTypeError. Wrap a single tuple inside a 1-element tuple:"%s" ((10, 20),).
- When formatting a single value with
- Escaping a literal percent sign (
):- Inside a format string containing
%s(or any%specifier), write a literal%as("Progress: %s%%" % 85$\rightarrow$"Progress: 85%"), otherwise Python raisesValueError: incomplete format.
- Inside a format string containing
- Width padding and truncation modifiers (
%10s,%-10s,%.5s):%10sright-aligns text in a 10-character column (padded with spaces on the left),%-10sleft-aligns it, and%.5struncates the string to at most 5 characters ("%.5s" "abcdefgh"$\rightarrow$"abcde").
- Why
%sis still the gold standard insideloggingcalls:- Even in modern Python 3.12+ codebases that use f-strings everywhere else,
logger.info("User %s connected", user_id)passes%sand the raw arguments separately sologgingskips string interpolation completely whenINFOlogging is disabled.
- Even in modern Python 3.12+ codebases that use f-strings everywhere else,
Comparison of Common % Format Specifiers and Modern Equivalents
| Specifier | Underlying Conversion | Example Input $\rightarrow$ Output | Modern f-String Equivalent | Best Used When |
|---|---|---|---|---|
%s |
str(obj) (any Python object) |
"%s" % 42 $\rightarrow$ "42" |
f"{obj}" (or f"{obj!s}") |
logging messages (logger.info("Got %s", x)) or legacy Python 2/3 templates. |
%r |
repr(obj) (debugging representation) |
"%r" "hi" $\rightarrow$ "'hi'" |
f"{obj!r}" |
Logging exact quotes, escape characters (\n), or object types during debugging. |
%d / %i |
Signed decimal integer (int) |
"%04d" % 7 $\rightarrow$ "0007" |
f"{num:04d}" |
Enforcing numeric integer formatting with zero-padding or sign alignment. |
%f / %.2f |
Fixed-point floating-point number | "%.2f" % 3.14159 $\rightarrow$ "3.14" |
f"{val:.2f}" |
Controlling decimal precision in tabular numeric output or legacy templates. |
You must log in or register to comment.
