您在這裡

Format operator

23 二月, 2015 - 16:09

The format operator, % allows us to construct strings, replacing parts of the strings with the data stored in variables. When applied to integers, % is the modulus operator. But when the first operand is a string, % is the format operator.

The first operand is the format string, which contains one or more format sequences that specify how the second operand is formatted. The result is a string.

For example, the format sequence '%d' means that the second operand should be formatted as an integer (d stands for “decimal”):

>>> camels = 42>>> '%d' % camels'42'

The result is the string '42', which is not to be confused with the integer value 42.

A format sequence can appear anywhere in the string, so you can embed a value in a sentence:

>>> camels = 42>>> 'I have spotted %d camels.' % camels'I have spotted 42 camels.'

If there is more than one format sequence in the string, the second argument has to be a tuple. Each format sequence is matched with an element of the tuple, in order.

The following example uses '%d' to format an integer, '%g' to format a floatingpoint number (don’t ask why), and '%s' to format a string:

>>> 'In %d years I have spotted %g %s.' % (3, 0.1, 'camels')'In 3 years I have spotted 0.1 camels.'

The number of elements in the tuple has to match the number of format sequences in the string. Also, the types of the elements have to match the format sequences:

>>> '%d %d %d' % (1, 2)TypeError: not enough arguments for format string>>> '%d' % 'dollars'TypeError: illegal argument type for built-in operation

In the first example, there aren’t enough elements; in the second, the element is the wrong type.

The format operator is powerful, but it can be difficult to use. You can read more about it at docs.python.org/lib/typesseq-strings.html.