all Python 3Strings (str)function
% formatting (old style)
formatting
The old formatting style, through the % operator. %s — string, %d — integer, %f — float, %r — repr.
Syntax
'format %s' % value | 'format %(key)s' % dict
The right-hand operand of % is a tuple of arguments, so a tuple you want to insert as a value must be wrapped in another one — '%s' % (t,) — otherwise Python spreads it across the specifiers and fails with TypeError. %d applied to a float silently drops the fractional part. New code uses f-strings, yet %-style survives in logging: logging.info('x=%s', x) defers the substitution until the record is actually emitted.
Examples
print('Hello, %s!' % 'World')
# → 'Hello, World!'
print('x=%d, y=%d' % (3, 5))
# → 'x=3, y=5'
print('pi=%.3f' % 3.14159)
# → 'pi=3.142'
print('%(name)s is %(age)d' % {'name': 'Bob', 'age': 25})
# → 'Bob is 25'
print('%05d' % 42)
# → '00042'
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy