The string .format() method

The .format() method of the str type is an extremely convenient way to format text exactly the way you want it.

Note

This method was added in Python 2.6.

Quite often, we want to embed data values in some explanatory text. For example, if we are displaying the number of nematodes in a hectare, it is a lot more meaningful to display it as "There were 37.9 nematodes per hectare" than just "37.9". So what we need is a way to mix constant text like "nematodes per hectare" with values from elsewhere in your program.

Here is the general form:

template.format(p0, p1, ..., k0=v0, k1=v1, ...)

The template is a string containing a mixture of one or more format codes embedded in constant text. The format method uses its arguments to substitute an appropriate value for each format code in the template.

The arguments to the .format() method are of two types. The list starts with zero or more positional arguments pi, followed by zero or more keyword arguments of the form ki=vi, where each ki is a name with an associated value vi.

Just to give you the general flavor of how this works, here's a simple conversational example. In this example, the format code “{0}” is replaced by the first positional argument (49), and “{1}” is replaced by the second positional argument, the string "okra".

>>> "We have {0} hectares planted to {1}.".format(49, "okra")
'We have 49 hectares planted to okra.'
>>>

In the next example, we supply the values using keyword arguments. The arguments may be supplied in any order. The keyword names must be valid Python names 

>>> "{monster} has now eaten {city}".format(
...     city='Tokyo', monster='Mothra')
'Mothra has now eaten Tokyo'

You may mix references to positional and keyword arguments:

>>> "The {structure} sank {0} times in {1} years.".format(
...   3, 2, structure='castle')
'The castle sank 3 times in 2 years.'

If you need to include actual “{” and “}” characters in the result, double them, like this:

>>> "There are {0} members in set {{a}}.".format(15)
'There are 15 members in set {a}.'

It also works in this way:

>>> "Hello {}".format("World")
'Hello World


Share:

0 comments:

Post a Comment