Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting numbers consistently in Python

I have a series of numbers:

from numpy import r_
r_[10**(-9), 10**(-3), 3*10**(-3), 6*10**(-3), 9*10**(-3), 1.5*10**(-2)]

and I would like to have them displayed in a plot's legend in the form:

a 10^(b)

(with ^ meaning superscript)

so that e.g. the third number becomes 3 10^(-3).

I know I have to use Python's string formatting operator % for this, but I don't see a way to do this. Can someone please show me how (or show me an alternative way)?

like image 543
rubenvb Avatar asked Feb 22 '13 09:02

rubenvb


People also ask

What does %d and %s do in Python?

They are used for formatting strings. %s acts a placeholder for a string while %d acts as a placeholder for a number. Their associated values are passed in via a tuple using the % operator.

How do you format a number in Python?

When formatting the floating point number 123.4567 , we've specified the format specifier ^-09.3f . These are: ^ - It is the center alignment option that aligns the output string to the center of the remaining space. - - It is the sign option that forces only negative numbers to show the sign.

What is %d and %i in Python?

The reason why there are two is that, %i is just an alternative to %d ,if you want to look at it at a high level (from python point of view). Here's what python.org has to say about %i: Signed integer decimal. And %d: Signed integer decimal. %d stands for decimal and %i for integer.

What is %s and %R in Python?

The %s specifier converts the object using str(), and %r converts it using repr().


1 Answers

If you are sure you don't need more than a fixed number of places after the decimal dot, then:

>>> from numpy import r_
>>> a = r_[10**(-9), 10**(-3), 3*10**(-3), 6*10**(-3), 9*10**(-3), 1.5*10**(-2)]
>>> for x in a: print "%.1e"%x
... 
1.0e-09
1.0e-03
3.0e-03
6.0e-03
9.0e-03
1.5e-02

The catch here is that were you to use %.0e as a format, the last number would be printed as 1e-2

EDIT: Since you're using matplotlib, then it's a different story: you could use the TeX rendering engine. A quick-and-dirty example:

fig = plt.figure()
ax = fig.add_subplot(111)

x = 1.5*10**(-2)
l = ("%.0e"%x).split("e")
x_str = r"$ %s \times 10^{%s}$" % (l[0], l[1] )

ax.set_title(x_str)

plt.show()

which would indeed be a little cleaner with new .format string formatting.

EDIT2: Just for completeness and future reference, here's my take on the OP's way from the comments:

x = 1.5*10**(-2)
l = ("%.0e"%x).split("e")
x_str = r"$%s \times 10^{%s}$" % ( l[0], str(int(l[1])) )

Here I'm converting to an int and back to avoid leading zeros: -02 -> -2 etc.

like image 177
ev-br Avatar answered Sep 22 '22 20:09

ev-br