Open the way
Open the way

Reputation: 27329

Is fortran-like print in python possible?

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

Upvotes: 5

Views: 2986

Answers (6)

user5061
user5061

Reputation: 665

Fortran io is totally different to C style io in every way.

Go for Brendan's fortranformat package.

https://pypi.python.org/pypi/fortranformat

easy_install fortranformat

This allows arcane old fortran input files to be created with much less trial and error than trying to use C style string formatting.

Upvotes: 0

Brendan
Brendan

Reputation: 19353

You could also take a look at the fortranformat library on PyPI or the project page if you wanted to fully recreate FORTRAN text IO.

If you have any questions, send me an email (I wrote it).

Upvotes: 5

Enrico Carlesso
Enrico Carlesso

Reputation: 6934

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

Upvotes: 0

AndiDog
AndiDog

Reputation: 70128

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

Upvotes: 0

Stefano Borini
Stefano Borini

Reputation: 143785

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

Upvotes: 0

SilentGhost
SilentGhost

Reputation: 319561

>>> '%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.

Upvotes: 9

Related Questions