3

There is the str.format() method in python which I am familiar with however it does not work the same way as the format() function (global-builtin).

What is the purpose of the global format() function?

3 Answers 3

8

The format() function formats one value according to a formatting specification.

The str.format() method parses out a template, and then formats individual values. Each {value_reference:format_spec} specifier is basically applied to the matched value using the format() function, as format(referenced_value, format_spec).

In other words, str.format() is built on top of the format() function. str.format() operates on a full Format String Syntax string, format() operates on the matched values and applies just the Format Specification Mini-Language.

For example, in the expression

'The hex value of {0:d} is {0:02x}'.format(42)

the template string has two template slots, both formatting the same argument to the str.format() method. The first interpolates the output of format(42, 'd'), the other format(42, '02x'). Note that the second argument in both cases is the format specifier, e.g. everything that comes after the : colon in the template placeholder.

Use the format() function when you want to format just a single value, use str.format() when you want to place that formatted value in a larger string.

Under the hood, format() delegates to the object.__format__ method to let the value itself interpret the formatting specification. str.format() calls that method directly, but you should not rely on this. object.__format__ is a hook, in future format() might apply more processing to the result of that hook, or pre-process the format to pass in. This is all an implementation detail really, only interesting if you want to implement your own formatting language for your object type.

See PEP-3101 Advanced String Formatting for the original proposal that added str.format(), format() and the object.__format__ hook to the language.

4
  • However I cant do format("hello", "{hello}") is that a special case not handled by format?
    – Har
    Commented Jan 28, 2016 at 11:55
  • 1
    @Har: {hello} is a template, not a formatting specifier. The correct call is format('hello', ''); the format specifier is empty in your example. Commented Jan 28, 2016 at 11:57
  • The thing that confuses me is that Kikohs mentioned that format calls the string __ format __ method. So does this mean that the __ format __ method is not equivalent to str.format?
    – Har
    Commented Jan 28, 2016 at 11:59
  • @Har: technically speaking both str.format() and format() use the object.__format__ method to delegate how the format is applied. This is an implementation detail. Commented Jan 28, 2016 at 12:00
1

To add to Martin's answer, have a look at the PEP3101 proposal:

Each Python type can control formatting of its instances by defining a __format__ method. The __format__ method is responsible for interpreting the format specifier, formatting the value, and returning the resulting string.

The new, global built-in function 'format' simply calls this special method, similar to how len() and str() simply call their respective special methods:

def format(value, format_spec):
    return value.__format__(format_spec)

It is safe to call this function with a value of "None" (because the "None" value in Python is an object and can have methods.)

Several built-in types, including 'str', 'int', 'float', and 'object' define __format__ methods. This means that if you derive from any of those types, your class will know how to format itself.

More info here.

1

The str.format() method and the Formatter class share the same syntax for format strings (although in the case of Formatter, subclasses can define their own format string syntax).

Format strings contain “replacement fields” surrounded by curly braces {}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }}.

The grammar for a replacement field is as follows:

replacement_field ::=  "{" [field_name] ["!" conversion] [":" format_spec] "}"
field_name        ::=  arg_name ("." attribute_name | "[" element_index "]")*
arg_name          ::=  [identifier | integer]
attribute_name    ::=  identifier
element_index     ::=  integer | index_string
index_string      ::=  <any source character except "]"> +
conversion        ::=  "r" | "s"
format_spec       ::=  <described in the next section>

See also the Format Specification Mini-Language section.

The field_name itself begins with an arg_name that is either a number or a keyword. If it’s a number, it refers to a positional argument, and if it’s a keyword, it refers to a named keyword argument. If the numerical arg_names in a format string are 0, 1, 2, ... in sequence, they can all be omitted (not just some) and the numbers 0, 1, 2, ... will be automatically inserted in that order. Because arg_name is not quote-delimited, it is not possible to specify arbitrary dictionary keys (e.g., the strings '10' or ':-]') within a format string. The arg_name can be followed by any number of index or attribute expressions. An expression of the form '.name' selects the named attribute using getattr(), while an expression of the form '[index]' does an index lookup using getitem().

Changed in version 2.7: The positional argument specifiers can be omitted, so '{} {}' is equivalent to '{0} {1}'.

As Mentioned in the Python Documentation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.