Sub topic 11
The % operator in legacy code
This chapter assumes you can read f-strings and the format specification mini-language from the earlier chapters. You will meet the % operator in older scripts, in books written before Python 3.6, and in the logging module. You will rarely need to write it in new code, but you must be able to read it.
How it works
The % operator takes a format string on the left and the values on the right. Each placeholder in the string starts with % and ends with a type letter. The values replace the placeholders in order.
name = "Ada"
score = 93.456
print("%s scored %.1f" % (name, score))
print("%-10s|%5d|%10.2f" % ("Widget", 3, 3703.5))
print("Discount: %d%%" % 20)This prints:
Ada scored 93.5
Widget | 3| 3703.50
Discount: 20%The flags before the type letter work like the format spec after the colon in an f-string. - left-aligns, a number sets the width, and .2 sets the decimal places. To print a literal percent sign, write %%.
| Placeholder | Meaning | f-string equivalent |
|---|---|---|
| `%s` | `str()` of the value | `{x}` |
| `%r` | `repr()` of the value | `{x!r}` |
| `%d` | integer | `{x:d}` |
| `%f` | float, 6 decimals by default | `{x:f}` |
| `%x` | hexadecimal | `{x:x}` |
| `%%` | a literal percent sign | `%` |
Named placeholders
A placeholder can name a key, in which case the right-hand side must be a dictionary.
person = {"name": "Ada", "age": 36}
print("%(name)s is %(age)d years old" % person)This is the % version of str.format(**person). It is useful when the same dictionary feeds many messages.
Common errors
The operator checks the number and types of its values at run time. Most mistakes appear as a TypeError.
- Wrong number of values.
"%s and %s" % ("a",)raisesTypeError: not enough arguments for format string. Too many values raisesnot all arguments converted. - A tuple as the only value. A tuple on the right is treated as the list of values, not as one value.
- The wrong type letter.
"%d" % "5"raisesTypeErrorbecause%ddoes not convert strings."%d" % 5.9does not fail. It silently truncates to5.
The second error needs care:
point = (1, 2)
try:
print("Point: %s" % point)
except TypeError as err:
print("Error:", err)
print("Point: %s" % (point,))The first call fails with not all arguments converted during string formatting, because Python sees two values for one placeholder. Wrapping the tuple in a one-element tuple, (point,), fixes it. f-strings avoid this problem because each placeholder holds its own expression.
Where you still see it
The logging module uses %-style placeholders, and it fills them in only if the message is actually emitted:
import logging
logging.basicConfig(level=logging.INFO)
user = "ada"
logging.warning("User %s failed login %d times", user, 3)Pass the values as separate arguments, as shown, instead of formatting the string first. Logging then skips the formatting cost for suppressed messages. This is the one case where % placeholders are still the standard choice.
Converting to f-strings
When you modernize old code, translate each placeholder to its equivalent in the table above. "%-10s|%5d" % (a, b) becomes f"{a:<10}|{b:>5}". Note that %s left-aligns with -, while f-string strings left-align by default and numbers right-align by default.
Exercise
What does "%s: %d%%" % ("Done", 50) print, and why does "Items: %s" % [1, 2] work even though "Items: %s" % (1, 2) fails?
Show answer
The first prints Done: 50%, because %% produces a literal percent sign. A list is a single value, so it fills the one %s placeholder and prints Items: [1, 2]. A tuple is read as two separate values, which is more than the one placeholder accepts, so it raises TypeError.