tags:

views:

133

answers:

4

Hi,

is it possible some way to "print" in python in a fortran like way like this?

1     4.5656
2    24.0900
3   698.2300
4    -3.5000

So the decimal points is always in the same column, and we get always 3 or n decimal numbers?

Thanks

+7  A: 
>>> '%11.4f' % -3.5
'    -3.5000'

or the new style formatting:

>>> '{:11.4f}'.format(-3.5)
'    -3.5000'

more about format specifiers in the docs.

SilentGhost
oooh new style... shiny :)
Stefano Borini
hi thanks! and last thign, let's say i have three floats f1, f2, f3, how can I print them? I tried '%11.4f' % f1,f2,f3 but nothing
Werner
@werner: use `'%11.4f %11.4f %11.4f' % (f1,f2,f3)`
Adrien Plisson
A: 
for i in [(3, 4.534), (3, 15.234325), (10,341.11)]:
...     print "%5i %8.4f" % i
... 
    3   4.5340
    3  15.2343
   10 341.1100
Stefano Borini
A: 
print "%10.3f" % f

will right align the number f (as an aside: %-10.3f would be left-aligned). The string will be right-aligned to 10 characters (it doesn't work any more with > 10 characters) and exactly 3 decimal digits. So:

f = 698.230 # <-- 7 characters when printed with %10.3f
print "%10.3f" % f # <-- will print "   698.2300" (two spaces)

As a test for your example set do the following:

print "\n".join(map(lambda f: "%10.3f" % f, [4.5656, 24.09, 698.23, -3.5]))
AndiDog
A: 

You can use string.rjust(), this way:

a = 4.5656
b = 24.0900
c = 698.2300
d = -3.5000

a = "%.4f" % a
b = "%.4f" % b
c = "%.4f" % c
d = "%.4f" % d

l = max(len(a), len(b), len(c), len(d))

for i in [a, b, c, d]:
        print i.rjust(l+2)

Which gives:

~ $ python test.py 
    4.5656
   24.0900
  698.2300
   -3.5000
Enrico Carlesso