I have a function like this:
def PrintXY(x,y):
print('{:<10,.3g} {:<10,.3g}'.format(x,y) )
When I run this it's perfect:
>>> x = 1/3
>>> y = 5/3
>>> PrintXY(x,y)
0.333 1.67
But let's say that x
and y
are not guaranteed to exist:
>>> PrintXY(x, None)
unsupported format string passed to NoneType.__format__
In that case I'd like to print nothing, just empty space. I tried:
def PrintXY(x,y):
if y is None:
y = ''
print('{:<10,.3g} {:<10,.3g}'.format(x,y) )
But that gives:
ValueError: Unknown format code 'g' for object of type 'str'
How can I print whitespace if the number doesn't exist, and proper formating when the number does exist? I'd rather not print 0 or -9999 to signify an error.
I have separated it out to make it clear what the statements achieve. You can combine this into one line but it would make the code a bit harder to read
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))
Then running gives
In [179]: PrintXY(1/3., 1/2.)
...: PrintXY(1/3., None)
...: PrintXY(None, 1/2.)
...:
0.333 0.5
0.333
0.5
Another alternative to make sure your format remains consistent is to do
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))
You could try this:
def PrintXY(x=None, y=None):
print(''.join(['{:<10,.3g}'.format(n) if n is not None else '' for n in [x, y]]))
This you could easily expand to use x
, y
and z
.
You could just use different print
commands like this:
def PrintXY(x,y):
if y is None:
print('{:<10,.3g}'.format(x) )
else:
print('{:<10,.3g} {:<10,.3g}'.format(x,y) )
You can make code more readable and easy to understand the condition that you have in your problem statement, you can try this also:
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))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.