Skip to main content
The % operator in Python serves two distinct syntactic roles depending on the operand types: it acts as the modulo operator for numeric types and as the string interpolation operator for string and byte types.

Numeric Modulo

When applied to numeric types (int, float), the % operator calculates the remainder of the floor division between a dividend (left operand) and a divisor (right operand).
Mathematical Behavior: Unlike C or Java, Python’s modulo operator guarantees that the sign of the result always matches the sign of the divisor (b), not the dividend (a). The operation is mathematically defined by the following equation: r = a - (b * floor(a / b))
Floating-Point Operands: The % operator accepts float operands, returning a floating-point remainder based on the same floor division logic.
Note: Due to IEEE 754 precision limitations and the floor division behavior, the standard library math.fmod() is strictly recommended over the % operator when working with floats, as math.fmod() implements C-style modulo (matching the sign of the dividend).

String and Bytes Formatting

When the left operand is a str or bytes object, the % operator is overloaded to perform legacy printf-style formatting.
Evaluation Mechanics: The left operand is parsed for conversion specifiers (e.g., %s for string, %d for decimal integer, %f for float). The right operand must be a single value, a tuple of values, or a mapping object (such as a dict) that provides the data to substitute into the specifiers.
When using a tuple as the right operand, the number of elements in the tuple must exactly match the number of positional conversion specifiers in the format string, otherwise a TypeError is raised.
Tired of Poor Python Skills? Fix That With Deep Grasping!Learn More