2.1.5.1 More String Operations

String objects have one unique built-in operation: the %operator (modulo) with a string left argument interprets this string as a C sprintf() format string to be applied to the right argument, and returns the string resulting from this formatting operation.

The right argument should be a tuple with one item for each argument required by the format string; if the string requires a single argument, the right argument may also be a single non-tuple object.2.4The following format characters are understood: %, c, s, i, d, u, o, x, X, e, E, f, g, G. Width and precision may be a * to specify that an integer argument specifies the actual width or precision. The flag characters -, +, blank, # and 0 are understood. The size specifiers h, l or L may be present but are ignored. The %s conversion takes any Python object and converts it to a string using str() before formatting it. The ANSI features %p and %n are not supported. Since Python strings have an explicit length, %s conversions don't assume that '\0' is the end of the string.

For safety reasons, floating point precisions are clipped to 50; %f conversions for numbers whose absolute value is over 1e25 are replaced by %g conversions.2.5All other errors raise exceptions.

If the right argument is a dictionary (or any kind of mapping), then the formats in the string must have a parenthesized key into that dictionary inserted immediately after the "%" character, and each format formats the corresponding entry from the mapping. For example:

>>> count = 2
>>> language = 'Python'
>>> print'%(language)s has %(count)03d quote types.' % vars()
Python has 002 quote types.

In this case no * specifiers may occur in a format (since they require a sequential parameter list).

Additional string operations are defined in standard module string and in built-in module re.



Footnotes

... object.2.4
A tuple object in this case should be a singleton.
... conversions.2.5
These numbers are fairly arbitrary. They are intended to avoid printing endless strings of meaningless digits without hampering correct use and without having to know the exact precision of floating point values on a particular machine.


Send comments on this document to python-docs@python.org.


Banner.Novgorod.Ru