[Python-3000] String formatting: Conversion specifiers

Nick Coghlan ncoghlan at gmail.com
Wed Jun 7 15:21:35 CEST 2006

Bill Janssen wrote:
>> Here is a list of the conversion types that are currently supported by 
>> the % operator. First thing you notice is an eerie similarity between 
>> this and the documentation for 'sprintf'. :)
> Yes.  This is (or was) a significant advantage to the system.  Many
> people already had mastered the C/C++ printf system of specifiers, and
> could use Python's with no mental upgrades.  Is that no longer thought
> to be an advantage?

It's still to be preferred. Talin's latest version is still close enough to 
printf that using printf style formatters will 'do the right thing'. {0:s}, 
{0:.3f}, {0:5d}, {0:+8x} are all equivalent to their printf counterparts %s, 
%.3f, %5d, %+8x. (I thought doing it that way would be ambiguous, but Talin 
was able to figure out a way to preserve the compatibility while still adding 
the features we wanted).

The proposed Py3k version just adds some enhancements:
   - choose an arbitrary fill character
   - choose left or right alignment in the filled field
   - choose to have the sign before or after the field padding
   - choose to use () to denote negative numbers
   - choose to output integers as binary numbers

It also allows a class to override the handling of the formatting string 
entirely (so things like datetime can be first-class citizens in the 
formatting world).

>> So there's no need to tell the system 'this is a float' 
>> or 'this is an integer'.
> Except that the type specifier can affect the interpretation of the
> rest of the format string.  For example, %.3f means to print three
> fractional digits.

It's possible to define the format string independently of the type specifier 
- its just that some of the fields only have an effect when certain type 
specifiers are used (e.g. precision is ignored for string and integer type 

Talin's point is that because Python objects know their own type the 
formatting system can figure out a reasonable default type specifier (f for 
floats, d for integers and s for everything else). This means the whole 
conversion specifier can be made optional, including the type specifier.

>> The only way I could see this being useful is 
>> if you had a type and wanted it to print out as some different type - 
>> but is that really the proper role of the string formatter?
> Isn't that exactly what the string formatter does?  I've got a binary
> value and want to express it as a different type, a string?  Type
> punning at the low levels is often a useful debugging tool.

The latest version of the proposal explicitly states which builtin (str(), 
repr(), int() or float()) will be called before the value is formatted for 
each of the standard type specifiers.


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-3000 mailing list