TypeError: format string

先来看一段Python代码:

class Negate:
    def __init__(self, val):
        self.val = -val
    def __repr__(self):
        return str(self.val)

if __name__ == '__main__':
    print('{0:5}'.format(-5))

    x = Negate(5)
    print(x)
    print('{0:5}'.format(x))

这段代码在不同的Python版本下有不同的输出结果:

在Python 2.7中,输出为:

   -5

-5

-5

在Python 3.4中,输出为:

   -5

-5

TypeError: non-empty format string passed to object.__format__

在Python 3.6中,输出为:

   -5

-5

TypeError: unsupported format string passed to Negate.__format__

从上面的输出中可以看出,使用format来对齐数字和字符串时,其效果是不同的:

>>> '{0:5}'.format(-5)

'   -5'

>>> '{0:5}'.format('-5')

'-5   '

另外,对于Python3.4和Python 3.6中输出的TypeError错误,原因如下:

变量名x所引用的对象的类型为<class '__main__.Negate'>,而该类型没有自己的__format__()方法,所以只能使用默认继承自object对象的__format__()方法,而该默认方法不支持任何格式化选项(比如字段宽度),所以会引发上述TypeError错误。

对于上述TypeError错误,解决方法就是先把对象转换为字符串。转换方式有两种:

方式一:

print('{0:5}'.format(str(x)))

方式二:

print('{0!s:5}'.format(x))

使用其中的任何一种方式都可以。

原文地址:https://www.cnblogs.com/pyhou/p/7137569.html