Python number formatting

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 them to be displayed in the plot legend in the form:

a 10^(b)

(c ^stands for superscript)

so that, for example, the third number becomes 3 10^(-3).

I know that for this I have to use the Python string formatting operator %, but I see no way to do this. Can someone please show me how (or show me an alternative way)?

+5
source share
2 answers

If you are sure that you do not need more than a fixed number of places after the decimal point, 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

Here you will understand what to use %.0eas a format, the last number will be printed as1e-2

EDIT. matplotlib, : TeX. :

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

.format.

EDIT2: , OP :

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

int , : -02 β†’ -2 ..

+6
list_item = (multiply_number,degree_number)
displayed_items = [list_item, list_item, ....]
for item in displayed_items:
   print '{0}*10^({1})'.format(*item)

, . format(). * ( ).

0

All Articles