Formatting numbers consistently in Python

matplotlib, numpy, python, string-formatting

Solution

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.

Problem

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

Original source