Formatting numbers
Ken Koller
ken.koller at kla-tencor.com
Tue Sep 7 22:37:32 EDT 1999
>
You can use something like %+10.4f which means: 10 spaces for
everything, always include the sign, and use 4 digits after the decimal
point. You still have to figure out the max number you will represent
unless you go to exponential notation.
I'm sure there will be errers <sic> but something like:
for array in list:
for number in array:
print '%+10.4f' % (number,),
print
Here's a method from one of my classes that does something similar:
def __repr__(self):
str = ''
for r in range(self.size[1]-1,-1,-1):
r_str = ''
for c in range(self.size[0]):
r_str = r_str + '%+5.3f ' % (self.surface[r][c],)
r_str = r_str + '\n'
str = str + r_str
return str[:-1]
self.size is a tuple containing the dimensions of the arrary. The last
line strips the last newline.
> I'm learning Python and the documentation is great,
> but I haven't found an easy way to do the following.
> Given an array (2-D) of numbers, I'd like to print
> them out nicely formatted. The numbers can differ
> greatly in magnitude, so I'd like to use fewer
> decimal places for big numbers than for large ones.
>
> The output should look something like this (or better):
>
> 123456.78 -0.000123 -54231.321
> -4321567.1 9876.543 etc.
>
> Someone somewhere must have written a module to do
> this. Any pointers?
>
> P.S. I want to use the Python interpreter only at
> this time -- no tk or gtk.
>
> Thanks.
More information about the Python-list
mailing list