Python arrays and sting formatting options

Mensanator mensanator at aol.com
Mon Sep 29 19:08:28 EDT 2008


On Sep 29, 5:04 pm, Ivan Reborin <irebo... at delete.this.gmail.com>
wrote:
> Hello everyone,
>
> I was wondering if anyone here has a moment of time to help me with 2
> things that have been bugging me.
>
> 1. Multi dimensional arrays - how do you load them in python
> For example, if I had:
> -------
> 1 2 3
> 4 5 6
> 7 8 9
>
> 10 11 12
> 13 14 15
> 16 17 18
> -------
> with "i" being the row number, "j" the column number, and "k" the ..
> uhmm, well, the "group" number, how would you load this ?
>
> If fortran90 you would just do:
>
> do 10 k=1,2
> do 20 i=1,3
>
> read(*,*)(a(i,j,k),j=1,3)
>
> 20 continue
> 10 continue
>
> How would the python equivalent go ?
>
> 2. I've read the help on the next one but I just find it difficult
> understanding it.
> I have;
> a=2.000001
> b=123456.789
> c=1234.0001
>
> How do you print them with the same number of decimals ?
> (eg. 2.000, 123456.789, 1234.000)

>>> print '%0.3f' % 2.000001
2.000
>>> print '%0.3f' % 123456.789
123456.789
>>> print '%0.3f' % 1234.0001
1234.000


> and how do you print them with the same number of significant
> decimals?
> (eg. 2.000001, 123456.7, 1234.000 - always 8 decimals) ?

Your examples are 7 decimals (and you're not rounding).

Here's what 8 looks like (note that it's %0.7e because there
is always one digit to the left of the decimal point.)

>>> print '%0.7e' % 2.000001
2.0000010e+00
>>> print '%0.7e' % 123456.789
1.2345679e+05
>>> print '%0.7e' % 1234.0001
1.2340001e+03

If you actually meant 7, then use %0.6e:

>>> print '%0.6e' % 2.000001
2.000001e+00
>>> print '%0.6e' % 123456.789
1.234568e+05
>>> print '%0.6e' % 1234.0001
1.234000e+03


>
> Is something like this possible (built-in) in python ?

You can do more with gmpy.

>
> Really grateful for all the help and time you can spare.
>
> --
> Ivan




More information about the Python-list mailing list