以下代码给出 TypeError。
from sklearn.model_selection import KFold
kf = KFold(n_splits=5,shuffle=False).split(range(25))
print('{} {:^61} {}'.format('Iteration','Training set observations','Testing set observations'))
for iteration, data in enumerate(kf, start=3):
print('{:^9} {} {:^25}'.format(iteration, data[0], data[1]))
TypeError: unsupported format string passed to numpy.ndarray.format
当我们使用str(data[1])
时,代码给出了正确的输出
为什么需要这种显式字符串转换?
最佳答案
来自,例如 https://docs.python.org/3.4/library/string.html#format-specification-mini-language :
A general convention is that an empty format string (
""
) produces the same result as if you had calledstr()
on the value. A non-empty format string typically modifies the result.
因此,当 :^25
与 data[1]
匹配时,它会调用 data 的
对象,它是一个 __format__()
方法[1]numpy.ndarray
。这些对象遵循 Python 的 list
行为,即在格式字符串非空时引发 TypeError
。空格式字符串会导致在 data[0]
(在您的示例中)上调用 str()
,这样就可以工作。非空格式字符串(即 data[1]
的 :^25
)在 Python 中的列表上失败,因为 Python 中的标准列表可能是异构对象的集合因此单一格式规范可能不适用于像这样的列表:[1, 2.3, 'four']
。 numpy
只是遵循相同的约定。
另请参阅https://github.com/numpy/numpy/issues/5543针对 numpy
的 GitHub
页面上的未决问题。该问题似乎与您在帖子中提到的同一问题有关。
关于python - 为什么Python中的.format方法需要显式字符串转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52585752/