2

I have a series of numbers in the scientific format in a list:

A = [1e-2, 1e-3, 1e-4]

What I want to do is to change A into B:

B = ['1e-2','1e-3','1e-4']

I thought the conversion can be done by:

B = [str(A[ii]) for ii in range(len(A))]

But it gives:

B = ['0.01','0.001','0.0001']
jwm
  • 4,832
  • 10
  • 46
  • 78
  • `format(num, "e")` perhaps? – Tadhg McDonald-Jensen Jun 26 '17 at 19:18
  • @TadhgMcDonald-Jensen That's pretty neat actually. However, I tried it myself, and it is outputting: `'1.000000e-02'`. Which, to me *is* the same, but not *exactly* as expected. Still, pretty darn awesome. Didn't know format did that for numbers expressed that way. – idjaw Jun 26 '17 at 19:20
  • @TadhgMcDonald-Jensen: can you be more specific of where to use the format function – jwm Jun 26 '17 at 19:21
  • if you want only one digit then do `".0e"` for 'no digits after the decimal', and it'd be used in the list comp: `[format(num, "e") for num in A]` – Tadhg McDonald-Jensen Jun 26 '17 at 19:21
  • 1
    You don't have a series of numbers in scientific format. The scienctific format is just the string representation that you use to put in floats in a list. How the floats were formatted as string before converting to a float, the float doesn't know (nor does your program in retrievable way) – Anthon Jun 26 '17 at 19:21
  • Here is what I wrote. A = [1e-2, 1e-3, 1e-4] B = [str('%.e' % i) for i in A] print(B) output ['1e-02', '1e-03', '1e-04'] – Mr_U4913 Jun 26 '17 at 19:27

1 Answers1

3

Try ['{:.0e}'.format(float(x)) for x in A]

  • 3
    You don't need `str.format`, and you don't need the `float` call. `[format(x, '.0e') for x in A]` works just as well. – vaultah Jun 26 '17 at 19:23
  • @vaultah: Both are good solutions!! But yours are better! – jwm Jun 26 '17 at 19:24
  • I am getting `'1e-02'` instead of `'1e-2'`, is there a way to eliminate the 0 in the `02` part ? – Dean Feb 22 '21 at 21:21