在Python 2.7中,str.format()接受非字符串参数并__str__在格式化输出之前调用值的方法:
class Test:
def __str__(self):
return 'test'
t = Test()
str(t) # output: 'test'
repr(t) # output: '__main__.Test instance at 0x...'
'{0: <5}'.format(t) # output: 'test ' in python 2.7 and TypeError in python3
'{0: <5}'.format('a') # output: 'a '
'{0: <5}'.format(None) # output: 'None ' in python 2.7 and TypeError in python3
'{0: <5}'.format([]) # output: '[] ' in python 2.7 and TypeError in python3
Run Code Online (Sandbox Code Playgroud)
但是当我传递一个datetime.time对象时,我' <5'在Python 2.7和Python 3中得到了输出:
from datetime import time
'{0: <5}'.format(time(10,10)) # output: ' <5'
Run Code Online (Sandbox Code Playgroud)
将datetime.time对象传递给str.format()应该引发TypeError或格式化str(datetime.time),而是返回格式化指令.这是为什么?
vau*_*tah 10
'{0: <5}'.format(time(10, 10))结果调用time(10, 10).__format__,它返回<5的<5格式说明:
In [26]: time(10, 10).__format__(' <5')
Out[26]: ' <5'
Run Code Online (Sandbox Code Playgroud)
发生这种情况是因为time_instance.__format__尝试格式化time_instance使用time.strftime并且time.strftime不理解格式化指令.
In [29]: time(10, 10).strftime(' <5')
Out[29]: ' <5'
Run Code Online (Sandbox Code Playgroud)
该!s转换标志会告诉str.format打电话str的time渲染结果之前实例-它会调用str(time(10, 10)).__format__(' <5'):
In [30]: '{0!s: <5}'.format(time(10, 10))
Out[30]: '10:10:00'
Run Code Online (Sandbox Code Playgroud)