1

I have this list of list

a = [['c', '1.3e-8', '4.5e-8'], ['h', '3.4e-5', '2.3e-7', '2.3e-5']]

I want to format the 'e' strings only as

a = [[ 'c', '0.000000013', '0.000000045'], ['h', '0.000034', '0.00000023', '0.000023']]

How can I do this in Python? Thanks!

6
  • 5
    what have you tried until now? Why does the second list in the first line have 4 elements and 3 in the second line? Commented Apr 18, 2014 at 1:07
  • 1
    Do the sublists always have the same structure (a single letter string, followed by numeric ones)? Commented Apr 18, 2014 at 1:12
  • 2
    And why does the result for '1.3e-9' evaluate to '0.00000' (5 sig figs), while '4.5e-8' evaluates to '0.00000045' (8 sig figs)? Can you make your specification more clear please? Commented Apr 18, 2014 at 1:23
  • this is just an example. Lists have same number of elements but the first element is not a float looking string where as others are float looking strings. I want to format the 'e' part of strings, but want to keep the first element of the list. I am very new in learning Python. Thanks for your comments and I hope I am able to explain what I intend to do. Best! Commented Apr 18, 2014 at 1:40
  • You still haven't addressed several of the problems with your expected output. Again, why does '1.3e-9' -> '0.00000' while '4.5e-8' -> '0.00000045'? Why do both '2.3e-7' and '2.3e-5' -> '0.00023'?? Commented Apr 18, 2014 at 1:58

1 Answer 1

1

If you sure only first element is not a float.

from decimal import Decimal

a = [['c', '1.3e-8', '4.5e-8'], ['h', '3.4e-5', '2.3e-7', '2.3e-5']]

for inx, rec in enumerate(a):
    a[inx] = [rec[0]] + ['{:.{precise}f}'.format(Decimal(val),
                precise=int(val[-1])+1) for val in rec[1:]]

print(a)

Output:

[['c', '0.000000013', '0.000000045'], ['h', '0.000034', '0.00000023', '0.000023']]
Sign up to request clarification or add additional context in comments.

1 Comment

Your code gives TypeError, "cannot concatenate 'str' and 'int' objects.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.