Yet another Python textbook

Terry Reedy tjreedy at udel.edu
Thu Nov 22 23:12:42 CET 2012


On 11/22/2012 7:24 AM, Colin J. Williams wrote:

>  From my reading of the docs, it seems to me that the three following
> should be equivalent:

We read differently...
>
>    (a) formattingStr.format(values)

Where 'values' is multiple arguments

> with
>    (b) format(values, formattingStr)

"format(value[, format_spec])
Convert a value to a “formatted” representation, as controlled by 
format_spec."

I notice that you did not pass multiple args, but indeed just one.
A 'format_spec' is only part of a {} formatting field.

> or
>    (c) tupleOfValues.__format__(formattingStr

 >>> tuple.__format__
<method '__format__' of 'object' objects>

Which of to say, not specific to tuples.

> Example:
> print('{:-^14f}{:^14d}'.format(-25.61, 95 ))
> print(format((-25.61, 95), '{:-^14f}{:^14d}'))

"The interpretation of format_spec will depend on the type of the value 
argument, however there is a standard formatting syntax that is used by 
most built-in types: Format Specification Mini-Language." (The latter is 
link to the FSML.

'-^14f' and '^14d' are format_specs.
'{:-^14f}{:^14d}' is a format string that includes two fields with 
format specs. It is not a format spec in itself and is therefore invalid 
by the doc.

> (-25.61, 95 ).__format__('{:-^14f}{:^14d}')
>
> The second fails, perhaps because values can only be a single value.

You only passed one, but you did not pass a format spec and indeed there 
is none for tuples. As delivered, format specs only format strings and 
numbers as strings. Collection classes other than str recursively format 
their members using str() or repr() until they reach strings, numbers, 
or customs class instances with custom .__format__ methods.

> Should we retreat to %-formatting for now?

Nonsense. The issues above are the same for % formatting. If you try to 
format one object with two % format specs, it will fail for the same 
reason. Try the % equivalent of what failed.

'%-14f%14d' % ((-25.61, 95 ),)

-- 
Terry Jan Reedy




More information about the Python-list mailing list