Sub topic 11
The % operator in legacy code
This chapter assumes you know str, int, and float, tuples and dictionaries, and try/except. You should also have read the earlier chapters on f-strings, format specifications, and str.format(). You will probably never write new code with the % operator. You will read it, though, in older codebases, in tutorials written before Python 3.6, and in the logging module. The goal is to read it fluently, spot its traps, and convert it safely.
What the operator does
When the left operand of % is a string, Python treats the operator as string formatting rather than as a remainder. The string holds placeholders that start with %, and the right operand supplies the values.
name = "Ada"
score = 93.456
print("%s scored %.1f" % (name, score))This prints Ada scored 93.5. The placeholders are filled left to right from the tuple on the right. This style is called printf-style formatting because it copies the printf function of the C language.
A placeholder has this shape:
%[(key)][flags][width][.precision]typeOnly % and the type character are required. Everything else is optional and must appear in that order.
Conversion types
The type character decides how the value is converted.
| Type | Meaning | Example | Result |
|---|---|---|---|
| `%s` | `str(value)` | `"%s" % [1, 2]` | `[1, 2]` |
| `%r` | `repr(value)` | `"%r" % "hi"` | `'hi'` |
| `%d` or `%i` | Integer, decimal | `"%d" % 42` | `42` |
| `%f` | Fixed-point float | `"%f" % 2.5` | `2.500000` |
| `%e` | Scientific notation | `"%e" % 12345.678` | `1.234568e+04` |
| `%g` | Shorter of `%f` or `%e` | `"%g" % 0.0000123` | `1.23e-05` |
| `%x`, `%X` | Hexadecimal | `"%x" % 255` | `ff` |
| `%o` | Octal | `"%o" % 8` | `10` |
| `%c` | One character | `"%c" % 65` | `A` |
| `%%` | A literal percent sign | `"%d%%" % 50` | `50%` |
The %s and %r pair matches the str() versus repr() distinction from the earlier chapter. In f-strings the same choice is written !s and !r.
Two details surprise people who come from f-strings:
%fdefaults to six decimal places. Use%.2ffor two.%daccepts a float and truncates it toward zero, so"%d" % 3.9gives3. The f-stringf"{3.9:d}"raisesValueErrorinstead. The old behavior can silently hide a bug where a float should not have reached that line.
Width, precision, and flags
Width and precision work much as they do in the format specification mini-language, but the flags are different characters.
print("%-10s|%5d|%08.3f" % ("Widget", 3, 3.14159))
print("%+d %+d" % (5, -5))
print("%5.1f%%" % 12.345)
print("%*d" % (6, 42))This prints:
Widget | 3|0003.142
+5 -5
12.3%
42The flags behave as follows:
-left-aligns. Without it, values are right-aligned, including strings.0pads numbers with zeros instead of spaces.+always shows the sign.- A space in the flags position leaves a blank where a plus sign would go.
*takes the width or precision from the argument list. That is why"%*d" % (6, 42)consumes two values.
There is no thousands separator. The mini-language has f"{1234567:,}", and % has no equivalent. Code that needs grouped digits and uses % usually calls the locale module or builds the string by hand.
Passing the values
How you write the right operand controls how the values are matched.
A tuple for several values
With two or more placeholders, the right side must be a tuple whose length equals the number of placeholders.
try:
print("%s is %d years old" % ("Ada", 36, "extra"))
except TypeError as err:
print(err)
try:
print("%s is %d years old" % ("Ada",))
except TypeError as err:
print(err)Too many values produce not all arguments converted during string formatting. Too few produce not enough arguments for format string. Both errors appear when the code runs, not when the file is parsed. A rarely used branch with a mismatched count can survive in production for a long time. An f-string cannot have this bug, because each value sits inside its own placeholder.
The single-tuple trap
The tuple is part of the syntax, so a value that is itself a tuple gets unpacked.
point = (3, 4)
try:
print("Point: %s" % point)
except TypeError as err:
print(err)
print("Point: %s" % (point,))The first print fails with not all arguments converted during string formatting. Python reads point as two arguments for one placeholder. The fix is a one-element tuple, (point,). A bare single value such as "%s" % name works only because name is not a tuple. If name ever receives a tuple at run time, the line breaks. Defensive code in older projects therefore often wraps every single argument in a tuple.
A dictionary for named values
Putting a key in parentheses right after the % makes the right operand a mapping.
data = {"name": "Ada", "score": 93.456}
print("%(name)s scored %(score).1f" % data)
print("%(name)s again, and %(name)s once more" % data)Named placeholders let the same value appear several times and let the template reorder values without changing the call. You cannot mix named and positional placeholders in one string. A missing key raises KeyError.
Where you still meet it
The logging module
The standard logging module uses % placeholders in its message argument, but it does the formatting itself and does it lazily.
import logging
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
user = "ada"
attempts = 3
logging.warning("user %s failed %d times", user, attempts)
logging.debug("debug detail %s", {"expensive": "value"})Only the warning is printed: WARNING: user ada failed 3 times. The call passes the values as separate arguments, not with the % operator. If the level is disabled, as it is for the debug call, logging never builds the string. An f-string would build it before the call, whether or not the message is kept. For this reason the logging documentation and many linters still prefer the % style inside logging calls, even in new code. The format= argument above is also %-style, with named placeholders.
Bytes formatting
str.format() and f-strings do not exist for bytes. The % operator works on bytes since Python 3.5, so it is the way to build protocol messages such as b"%d bytes" % 12. The %s conversion on bytes requires a bytes-like value.
Old code and old examples
Scripts written for Python 2, and answers on older forums, use % almost exclusively. Python has no plan to remove it, and the documentation calls it "old string formatting". It keeps working, but new features go into f-strings and format().
Why new code avoids it
- A wrong argument count fails at run time and not at the point of writing.
- The tuple trap needs defensive wrapping.
- Values and placeholders are far apart in a long string, so mismatches are hard to see.
- Alignment, signs, and conversions use different characters from the mini-language, so you must remember two syntaxes.
- It cannot call methods or evaluate expressions in the placeholder, and it has no
=debugging form. %sand%daccept more types than you expect. That is convenient, but it hides type mistakes.
Converting legacy code
Most conversions are mechanical.
| Legacy `%` form | f-string |
|---|---|
| `"%s" % x` | `f"{x}"` |
| `"%r" % x` | `f"{x!r}"` |
| `"%d" % n` | `f"{n:d}"` (but `int(n)` first if `n` may be a float) |
| `"%.2f" % x` | `f"{x:.2f}"` |
| `"%-10s" % s` | `f"{s:<10}"` |
| `"%5d" % n` | `f"{n:>5}"` |
| `"%08.3f" % x` | `f"{x:08.3f}"` |
| `"%x" % n` | `f"{n:x}"` |
| `"%(name)s" % d` | `f"{d['name']}"` or `"{name}".format(**d)` |
| `"%d%%" % p` | `f"{p}%"` |
Two cases need care. First, a template stored in a database or a file cannot become an f-string, because an f-string must be written literally in source code. Use str.format() or string.Template for those. Second, if the old code relied on %d truncating a float, the converted code needs an explicit int() call, or the output will change.
Common mistakes
- Forgetting
%%when a literal percent sign follows a placeholder."%d% done" % 5raisesValueError: unsupported format character, because Python reads% das a flag and conversion. - Writing
"Total: %s" % a, band expecting two values. Operator precedence makes this a tuple of the formatted string andb. Wrap the values in parentheses. - Applying
%to a string that already contains user text with stray%characters. If the user's text is the template, the operator may raise errors or fail on a missing key. Treat user text as a value, never as the template. - Mixing positional and
%(name)splaceholders in one string.
Exercise
This function is meant to print a coordinate, but it raises TypeError when it is called as show((3, 4)). Explain why, then rewrite it two ways: once still using % and once as an f-string. def show(point): print("Coordinate: %s" % point)
Show answer
The right operand is a tuple, so % treats it as two arguments for a single placeholder and raises "not all arguments converted during string formatting". With %, wrap the value in a one-element tuple: print("Coordinate: %s" % (point,)). As an f-string: print(f"Coordinate: {point}"). Both print Coordinate: (3, 4).
Exercise
Convert print("%-8s|%6.2f|%3d%%" % (name, price, pct)) to an f-string that produces identical output.
Show answer
print(f"{name:<8}|{price:6.2f}|{pct:3d}%"). Numbers are right-aligned by default, so no ">" is needed. The literal percent sign no longer needs doubling, because an f-string has no special meaning for a lone %.