gpt4 book ai didi

python - 使用 format() 打印 numpy timedelta64

转载 作者:行者123 更新时间:2023-11-28 21:18:43 25 4
gpt4 key购买 nike

我想以格式化的方式打印一个 numpy.timedelta64() 值。直接方法效果很好:

>>> import numpy as np
>>> print np.timedelta64(10,'m')
10 minutes

我猜这来自 __str__() 方法

>>> np.timedelta64(10,'m').__str__()
'10 minutes'

但是当我尝试使用 format() 函数打印它时,出现以下错误:

>>> print "my delta is : {delta}".format(delta=np.timedelta64(10,'m'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: don't know how to convert scalar number to long

我想了解“string”.format() 函数的底层机制,以及为什么它在这种特殊情况下不起作用。

最佳答案

根据Format String Syntax documentation :

The conversion field causes a type coercion before formatting. Normally, the job of formatting a value is done by the __format__() method of the value itself. However, in some cases it is desirable to force a type to be formatted as a string, overriding its own definition of formatting. By converting the value to a string before calling __format__(), the normal formatting logic is bypassed.

>>> np.timedelta64(10,'m').__format__('')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: don't know how to convert scalar number to long

通过附加 !s conversion flag , 你可以强制它使用 str :

>>> "my delta is : {delta!s}".format(delta=np.timedelta64(10,'m'))
'my delta is : 10 minutes'

关于python - 使用 format() 打印 numpy timedelta64,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26043994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com