0

PEP 3101 specifies Advanced String Formatting. Among other things, it defines a specification of a new syntax for format strings (eg. {:.2f}) and how custom types can control their own formatting. This is done by implementing:

def __format__(value, format_spec):
     # Your code here

The string formatting code can include a conversion flag. For example: "{0!r:20}".format("Hello"), where !r means convert the the value to a string using repr(). However, __format__ only gets the value after the colon : (i.e. the format_spec). I would like to know is the reason (i.e. the design decision, not the code) why? I think that providing everything after the the ! will be more flexible.

4

1 回答 1

1

冒号之前的部分仅用于字符串格式化,是一个模板函数,与格式化实际值本身无关。

冒号后面的部分单独处理,也可以用format()函数指定:

>>> format(234, '02x')
'ea'

将数字格式化为最少 2 个字符的小写零填充十六进制数。正是这个功能.__format__()让您能够融入其中;这是格式化值的业务端。

冒号之前的部分指定field_name字符串格式化程序如何检索要格式化的值。格式化值时,如何确定字段并不重要。field_name仅用于定位要调用的值,.__format__()并为该值指定替代转换方法(!r!s)。

请注意,通过使用!r.__format__()方法将被忽略并被.__repr__()使用!这同样适用于!s.__str__()

>>> class Foo(object):
...     def __repr__(self): return '<Foo repr>'
...     def __str__(self): return 'Foo as string'
...     def __format__(self, spec): return 'Formatting Foo as {}'.format(spec)
... 
>>> '{:02x}'.format(Foo())
'Formatting Foo as 02x'
>>> '{!s}'.format(Foo())
'Foo as string'
>>> '{!r}'.format(Foo())
'<Foo repr>'
于 2013-07-02T14:48:17.740 回答