Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #33812

Re: Yet another Python textbook

References (4 earlier) <31a82817-8c9b-4dd2-a468-89d8d081fd1b@googlegroups.com> <mailman.96.1353445247.29569.python-list@python.org> <50AD0962.5080002@ncf.ca> <mailman.180.1353536254.29569.python-list@python.org> <50AE1986.2080605@ncf.ca>
From Ian Kelly <ian.g.kelly@gmail.com>
Date 2012-11-22 11:27 -0700
Subject Re: Yet another Python textbook
Newsgroups comp.lang.python
Message-ID <mailman.210.1353608868.29569.python-list@python.org> (permalink)

Show all headers | View raw


On Thu, Nov 22, 2012 at 5:24 AM, Colin J. Williams <cjw@ncf.ca> wrote:
> From my reading of the docs, it seems to me that the three following should
> be equivalent:
>
>   (a) formattingStr.format(values)
> with
>   (b) format(values, formattingStr)
> or
>   (c) tupleOfValues.__format__(formattingStr
>
> Example:
> print('{:-^14f}{:^14d}'.format(-25.61, 95 ))
> print(format((-25.61, 95), '{:-^14f}{:^14d}'))
> (-25.61, 95 ).__format__('{:-^14f}{:^14d}')
>
> The second fails, perhaps because values can only be a single value.
> The third fails, the reason is unclear.

The latter two (which are more or less equivalent) fail because they are
intended for invoking the formatting rules of a single value.  The
string argument to each of them is not a format string, but a "format
specification", which in a format string is only the part that goes
inside the curly braces and after the optional colon.  For example, in
this format string:

>>> 'Hello world {0!s:_>4s}'.format(42)
'Hello world __42'

The format specifier here is "_>4s":

>>> format('42', '_>4s')
'__42'

The valid format specifiers depend upon the type of the object being formatted:

>>> format(42, '04x')
'002a'

>>> format(datetime(2012, 11, 22, 11, 17, 0), 'The time is %Y %d %m %H:%M:%S')
'The time is 2012 22 11 11:17:00'

Custom types can implement custom format specifications by overriding
the __format__ method:

>>> class Foo:
...     def __init__(self, value):
...         self.value = value
...     def __format__(self, spec):
...         if spec == 'a':
...             return str(self.value)
...         if spec == 'b':
...             return ''.join(reversed(str(self.value)))
...         raise ValueError("Unknown format code {!r}".format(spec))
...
>>> format(Foo(42), 'a')
'42'
>>> format(Foo(42), 'b')
'24'

The same format specifications can then also be passed to str.format:

>>> '{0:a} reversed is {0:b}'.format(Foo(42))
'42 reversed is 24'

Unfortunately, there does not seem to be a good reference to the
format specifications available for built-in types beyond basic
strings and numbers.  I only knew about the datetime example because
it is used in an example in the str.format docs.  The
datetime.__format__ implementation (which seems to be just a thin
wrapper of datetime.strftime) does not seem to be documented anywhere
in the datetime module docs.

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Re: Yet another Python textbook Chris Angelico <rosuav@gmail.com> - 2012-11-20 19:09 +1100
  Re: Yet another Python textbook wxjmfauth@gmail.com - 2012-11-20 06:57 -0800
    Re: Yet another Python textbook Chris Angelico <rosuav@gmail.com> - 2012-11-21 08:00 +1100
      Re: Yet another Python textbook wxjmfauth@gmail.com - 2012-11-21 06:49 -0800
      Re: Yet another Python textbook wxjmfauth@gmail.com - 2012-11-21 06:49 -0800
      Re: Yet another Python textbook "Colin J. Williams" <cjw@ncf.ca> - 2012-11-21 12:03 -0500
        Re: Yet another Python textbook Chris Angelico <rosuav@gmail.com> - 2012-11-22 09:17 +1100
          Re: Yet another Python textbook "Colin J. Williams" <cjw@ncf.ca> - 2012-11-22 07:24 -0500
            Re: Yet another Python textbook Ian Kelly <ian.g.kelly@gmail.com> - 2012-11-22 11:27 -0700
              Re: Yet another Python textbook "Colin J. Williams" <cjw@ncf.ca> - 2012-11-22 17:41 -0500
                Re: Yet another Python textbook Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-11-23 03:26 +0000
            Re: Yet another Python textbook Terry Reedy <tjreedy@udel.edu> - 2012-11-22 17:12 -0500
        Re: Yet another Python textbook Dave Angel <d@davea.name> - 2012-11-21 17:58 -0500
        Re: Yet another Python textbook Ian Kelly <ian.g.kelly@gmail.com> - 2012-11-21 16:11 -0700
        Re: Yet another Python textbook Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-11-21 23:26 +0000
        Re: Yet another Python textbook Mark Lawrence <breamoreboy@yahoo.co.uk> - 2012-11-21 23:32 +0000
        Re: Yet another Python textbook Ian Kelly <ian.g.kelly@gmail.com> - 2012-11-21 17:19 -0700
        Re: Yet another Python textbook Terry Reedy <tjreedy@udel.edu> - 2012-11-21 23:04 -0500
    Re: Yet another Python textbook Mark Lawrence <breamoreboy@yahoo.co.uk> - 2012-11-20 21:55 +0000
    Re: Yet another Python textbook Chris Angelico <rosuav@gmail.com> - 2012-11-21 09:25 +1100

csiph-web