Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python print floats padded with spaces instead of zeros

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)?

like image 703
Alnitak Avatar asked Aug 03 '17 08:08

Alnitak


2 Answers

What about this?

>>> '{0: <8}|'.format(str(myfloat))
'0.002   |'

Edit: following Gall's comment, this suffices

>>> '{0: <8}|'.format(myfloat)
'0.002   |'
like image 73
Gribouillis Avatar answered Oct 21 '22 01:10

Gribouillis


Try this:

print(str(myfloat).ljust(6, ' ') + '|')

If you need more white spaces just change 6 to whatever you want.

like image 25
Thomas Jr Avatar answered Oct 21 '22 02:10

Thomas Jr