[Python-3000] Format specifier proposal

Ron Adam rrr at ronadam.com
Wed Aug 15 23:29:40 CEST 2007



Adam Olsen wrote:
> On 8/15/07, Ron Adam <rrr at ronadam.com> wrote:
>>
>> Andrew James Wade wrote:
>>> On Tue, 14 Aug 2007 21:12:32 -0500
>>> Ron Adam <rrr at ronadam.com> wrote:
>>>> What I was thinking of was just a simple left to right evaluation order.
>>>>
>>>>      "{0:spec1, spec2, ... }".format(x)
>>>>
>>>> I don't expect this will ever get very long.
>>> The first __format__ will return a str, so chains longer than 2 don't
>>> make a lot of sense. And the delimiter character should be allowed in
>>> spec1; limiting the length of the chain to 2 allows that without escaping:
>>>
>>>     "{0:spec1-with-embedded-comma,}".format(x)
>>>
>>> My scheme did the same sort of thing with spec1 and spec2 reversed.
>>> Your order makes more intuitive sense; I chose my order because I
>>> wanted the syntax to be a generalization of formatting strings.
>>  >
>>> Handling the chaining within the __format__ methods should be all of
>>> two lines of boilerplate per method.
>> I went ahead and tried this out and it actually cleared up some difficulty
>>   in organizing the parsing code.  That was a very nice surprise. :)
>>
>>      (actual doctest)
>>
>>      >>> import time
>>      >>> class GetTime(object):
>>      ...     def __init__(self, time=time.gmtime()):
>>      ...         self.time = time
>>      ...     def __format__(self, spec):
>>      ...         return fstr(time.strftime(spec, self.time))
>>
>>      >>> start = GetTime(time.gmtime(1187154773.0085449))
>>
>>      >>> fstr("Start: {0:%d/%m/%Y %H:%M:%S,<30}").format(start)
>>      'Start: 15/08/2007 05:12:53           '
> 
> Caveat: some date formats include a comma.  I think the only
> workaround would be splitting them into separate formats (and using
> the input date twice).

Maybe having an escaped comma?   '\,'

It really isn't any different than escaping quotes.  It could be limited to 
just inside format {} expressions I think.

Using raw strings with '\54' won't work.

Ron



More information about the Python-3000 mailing list