zoukankan      html  css  js  c++  java
  • 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))

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

  • 相关阅读:
    oracle中查看sql语句的执行计划
    linux跨主机复制文件
    linux主机登录另一台linux主机
    JVM内存监控:visualVM jconsole jstatd jmap
    linux shell自动输入实现
    awk 截取字符串
    dos2unix dos文本转换为linux文本 /bin/bas^M:bad interpreter
    EasyUI
    Jquery插件 easyUI属性汇总
    移动端省际联动插件mobiscroll
  • 原文地址:https://www.cnblogs.com/pyhou/p/7137569.html
Copyright © 2011-2022 走看看