猿问

Python 条件打印格式

我有一个这样的功能:


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 来表示错误。


森栏
浏览 242回答 3
3回答

浮云间

我已经把它分开了,以明确这些语句的作用。您可以将其合并为一行,但这会使代码更难阅读def PrintXY(x,y):&nbsp; &nbsp; x_str = '{:.3g}'.format(x) if x else ''&nbsp; &nbsp; y_str = '{:.3g}'.format(y) if y else ''&nbsp; &nbsp; print('{:<10} {:<10}'.format(x_str, y_str))然后运行给出In [179]: PrintXY(1/3., 1/2.)&nbsp; &nbsp; &nbsp;...: PrintXY(1/3., None)&nbsp; &nbsp; &nbsp;...: PrintXY(None, 1/2.)&nbsp; &nbsp; &nbsp;...:0.333&nbsp; &nbsp; &nbsp; 0.50.333&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;0.5确保您的格式保持一致的另一种选择是def PrintXY(x,y):&nbsp; &nbsp; fmtr = '{:.3g}'&nbsp; &nbsp; x_str = fmtr.format(x) if x else ''&nbsp; &nbsp; y_str = fmtr.format(y) if y else ''&nbsp; &nbsp; print('{:<10} {:<10}'.format(x_str, y_str))

蝴蝶不菲

你可以试试这个:def PrintXY(x=None, y=None):&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; print(''.join(['{:<10,.3g}'.format(n) if n is not None else '' for n in [x, y]]))您可以轻松扩展以使用x,y和z。

qq_笑_17

您可以使代码更具可读性且易于理解问题陈述中的条件,您也可以尝试以下操作:def PrintXY(x,y):&nbsp; &nbsp; formatter = None&nbsp; &nbsp; if x is None and y is None:&nbsp; &nbsp; &nbsp; &nbsp; x, y = '', ''&nbsp; &nbsp; &nbsp; &nbsp; formatter = '{} {}'&nbsp; &nbsp; if x is None:&nbsp; &nbsp; &nbsp; &nbsp; y = ''&nbsp; &nbsp; &nbsp; &nbsp; formatter = '{} {:<10,.3g}'&nbsp; &nbsp; if y is None:&nbsp; &nbsp; &nbsp; &nbsp; x = ''&nbsp; &nbsp; &nbsp; &nbsp; formatter = '{:<10,.3g} {}'&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; formatter = '{:<10,.3g} {:<10,.3g}'&nbsp; &nbsp; print(formatter.format(x,y))
随时随地看视频慕课网APP

相关分类

Python
我要回答