format() not behaving as expected

MRAB python at mrabarnett.plus.com
Fri Jun 29 19:41:29 CEST 2012


On 29/06/2012 18:19, Josh English wrote:
> On Friday, June 29, 2012 10:02:45 AM UTC-7, MRAB wrote:
>>
>> The ".format" method accepts multiple arguments, so the placeholders in
>> the format string need to specify which argument to format as well as
>> how to format it (the format specification after the ":").
>>
>> The "format" function, on the other hand, accepts only a single
>> argument to format, so it needs only the format specification, and
>> therefore can't accept subscripting or attributes.
>>
>>  >>> c = "foo"
>>  >>> print "{0:s}".format(c)
>> foo
>>  >>> format(c, "s")
>> 'foo'
>
> Thank you. That's beginning to make sense to me. If I understand this,
 > everything between the braces is the format specification,
> and the format specification doesn't include the braces, right?
>
No, the format specification is the part after the ":" (if present), as
in the example.

Here are more examples:

 >>> c = "foo"
 >>> print "{0}".format(c)
foo
 >>> format(c, "")
'foo'
 >>> print "To 2 decimal places: {0:0.2f}".format(1.2345)
To 2 decimal places: 1.23
 >>> print format(1.2345, "0.02f")
1.23



More information about the Python-list mailing list