I have a float myfloat = 0.002
I want to print with space padding ' '
instead of trailing zeros.
Let's say I want to print myfloat
with space-padding right-justified to 5 spaces. For clarity I will print '|'
after my float.
What I want:
0.002 |
What padded printing (I know of) gives:
>>> print(str(myfloat) + '|') # no padding, formatting
0.002|
>>> print('%.5f' % myfloat + '|')
0.00200|
>>> print('{0:<5f}|'.format(myfloat))
0.002000|
>>> print('{0:.5f}|'.format(myfloat))
0.00200|
I know print('{0:<Xf}|'.format(myfloat))
pads with spaces after X > 8 or so. I do not want any trailing zeros.
I am printing multiple floats on the same line. They have varying string lengths and I want them evenly justified with space padding rather than zeros, so a static padding string will not work.
For instance, lets say I want to print the contents of myfloatlist1 = [0.01, 0.002, 0.0003, 0.00004]
and myfloatlist2 = [0.00004, 0.0003, 0.002, 0.01]
on a two lines, each with the same spaced padding:
0.01 0.002 0.0003 0.00004
0.00004 0.0003 0.002 0.01
Is there anyway to pad float prints with spaces (without converting the float to a string or something)?
What about this?
>>> '{0: <8}|'.format(str(myfloat))
'0.002 |'
Edit: following Gall's comment, this suffices
>>> '{0: <8}|'.format(myfloat)
'0.002 |'
Try this:
print(str(myfloat).ljust(6, ' ') + '|')
If you need more white spaces just change 6 to whatever you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With