Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

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).
result = a % b
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))

# Positive divisor: result is always positive or zero
10 % 3    # Evaluates to 1
-10 % 3   # Evaluates to 2


# Negative divisor: result is always negative or zero
10 % -3   # Evaluates to -2
-10 % -3  # Evaluates to -1
Floating-Point Operands: The % operator accepts float operands, returning a floating-point remainder based on the same floor division logic.
5.5 % 2.0  # Evaluates to 1.5
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.
formatted_string = format_string % values
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.

# Tuple substitution (positional)
"%s is %d years old." % ("Alice", 30)

# Evaluates to: 'Alice is 30 years old.'


# Dictionary substitution (named mapping)
"%(name)s is %(age)d years old." % {"name": "Bob", "age": 25}

# Evaluates to: 'Bob is 25 years old.'
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.
Master Python with Deep Grasping Methodology!Learn More