Formatting exhibitors Without e or E

I have a list of the following type: list = [1, 3, 4.23123e-07]

I would like to write this list to a text file. I would like the file to look like this:

1 
3
4.231-7

For an exponential term, I would like to get rid of eany previous zeros in the exponent itself, so from 4.23123e-07to 4.231-7.

Is there a way to do this other than looping in my list and placing in a string 4.231-7instead of an integer 4.23123e-07?

+4
source share
2 answers

You can remove any eof the string, as well as any zeros following +or or -:

import re
values = [1, 3, 4.23123e-07]

def format_without_e(number):
  no_e = re.sub('e', '', str(number), re.IGNORECASE)
  return re.sub('(?<=[+-])0+', '', no_e)

formatted_numbers = [format_without_e(value) for value in values]

print(formatted_numbers)
# ['1', '3', '4.23123-7']

print("\n".join(formatted_numbers))
# 1
# 3
# 4.23123-7
+4
source

%g re . @MadPhysicist .

import re

[re.sub('e([-+])?[0]*',r"\1", '%.4g'%s) for s in l]

In [46]: l = [1, 3, 4.23123e-07]

In [47]: [re.sub('e([-+])?[0]*',r"\1", '%.4g'%s) for s in l]
Out[47]: ['1', '3', '4.231-7']
+1

Source: https://habr.com/ru/post/1680226/


All Articles