代码之家  ›  专栏  ›  技术社区  ›  Stewart

python条件打印格式

  •  2
  • Stewart  · 技术社区  · 7 年前

    我有这样的功能:

    def PrintXY(x,y):
        print('{:<10,.3g} {:<10,.3g}'.format(x,y) )
    

    当我运行这个时,它是完美的:

    >>> x = 1/3
    >>> y = 5/3
    >>> PrintXY(x,y)
    0.333      1.67
    

    但是我们可以这么说 x y 不保证存在:

    >>> PrintXY(x, None)
    unsupported format string passed to NoneType.__format__
    

    如果是那样的话,我不想打印任何东西,只是空白。我试过:

    def PrintXY(x,y):
        if y is None: 
            y = ''
        print('{:<10,.3g} {:<10,.3g}'.format(x,y) )
    

    但这给了我们:

    ValueError: Unknown format code 'g' for object of type 'str'
    

    如果数字不存在,如何打印空白,如果数字存在,如何正确格式化?我宁愿不打印0或-9999来表示错误。

    4 回复  |  直到 7 年前
        1
  •  6
  •   Stewart    7 年前

    我把它分开了,以清楚地说明这些陈述取得了什么效果。您可以将其合并为一行,但这会使代码更难阅读。

    def PrintXY(x,y):
        x_str = '{:.3g}'.format(x) if x else ''
        y_str = '{:.3g}'.format(y) if y else ''
        print('{:<10} {:<10}'.format(x_str, y_str))
    

    那么跑步给了

    In [179]: PrintXY(1/3., 1/2.)
         ...: PrintXY(1/3., None)
         ...: PrintXY(None, 1/2.)
         ...:
    0.333      0.5
    0.333
               0.5
    

    另一种确保格式保持一致的方法是

    def PrintXY(x,y):
        fmtr = '{:.3g}'
        x_str = fmtr.format(x) if x else ''
        y_str = fmtr.format(y) if y else ''
        print('{:<10} {:<10}'.format(x_str, y_str))
    
        2
  •  2
  •   Hein Wessels    7 年前

    你可以试试这个:

    def PrintXY(x=None, y=None):        
        print(''.join(['{:<10,.3g}'.format(n) if n is not None else '' for n in [x, y]]))
    

    这个你可以很容易地扩展使用 x , y z .

        3
  •  0
  •   Cornholio    7 年前

    你可以用不同的 print 这样的命令:

    def PrintXY(x,y):
        if y is None: 
            print('{:<10,.3g}'.format(x) )
        else:
            print('{:<10,.3g} {:<10,.3g}'.format(x,y) )
    
        4
  •  0
  •   Ashish    7 年前

    您可以使代码更易于阅读和理解问题语句中的条件,也可以尝试以下方法:

    def PrintXY(x,y):
        formatter = None
    
        if x is None and y is None:
            x, y = '', ''
            formatter = '{} {}'
        if x is None:
            y = ''
            formatter = '{} {:<10,.3g}'
        if y is None:
            x = ''
            formatter = '{:<10,.3g} {}'
        else:
            formatter = '{:<10,.3g} {:<10,.3g}'
    
        print(formatter.format(x,y))