在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
但是当我传递一个datetime.time
对象时,我在Python 2.7和Python 3中得到' <5'
作为输出:
from datetime import time
'{0: <5}'.format(time(10,10)) # output: ' <5'
将datetime.time
对象传递给str.format()
应该引发TypeError
或格式str(datetime.time)
,而是返回格式化指令。那是为什么?
答案 0 :(得分:10)
'{0: <5}'.format(time(10, 10))
会调用time(10, 10).__format__
,该<5
会为<5
格式说明符返回In [26]: time(10, 10).__format__(' <5')
Out[26]: ' <5'
:
time_instance
这是因为time_instance.__format__
尝试使用time.strftime
格式化time.strftime
,而In [29]: time(10, 10).strftime(' <5')
Out[29]: ' <5'
并不了解格式化指令。
!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'
:
{{1}}
答案 1 :(得分:2)
datetime
个对象支持datetime.strftime()
选项:
>>> from datetime import time
>>> '{0:%H}'.format(time(10,10))
'10'
该格式包括对文字文本的支持:
>>> time(10, 10).strftime('Hour: %H')
'Hour: 10'
>5
格式被视为文字文字。您可以使用以下格式将时间安排到5个字符的列中:
'{0:%H:%M}'