开发者

Is fortran-like print in python possible?

开发者 https://www.devze.com 2022-12-21 18:51 出处:网络
is i开发者_如何学运维t possible some way to \"print\" in python in a fortran like way like this?

is i开发者_如何学运维t 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


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


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


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


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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号