我有这样的功能:
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来表示错误。
发布于 2018-09-11 10:05:55
我把它分开,以清楚说明这些发言取得了什么成果。您可以将其合并成一行,但这会使代码更难阅读。
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))发布于 2018-09-11 10:10:11
你可以试试这个:
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。
发布于 2018-09-11 10:09:22
您只需使用以下不同的print命令:
def PrintXY(x,y):
if y is None:
print('{:<10,.3g}'.format(x) )
else:
print('{:<10,.3g} {:<10,.3g}'.format(x,y) )https://stackoverflow.com/questions/52273431
复制相似问题