Here is a slightly more flexible answer (does either 'e'
or 'E'
to separate mantissa and exponent, is forgiving of missing/bad arguments). But I am upvoting the answer from @AnuragUniyal because that answer is so compact.
def efmte(x, n=6, m=2, e='e', nmax=16):
def _expc(s): # return exponent character of e-formatted float
return next(filter(lambda character: character in {'E', 'e'}, s))
def _pad0(s, n): # return string padded to length n
return ('{0:0>' + str(n) + '}').format(s)
def _efmtes(s, n): # reformat e-formatted float: n e-digits
m, e, p = s.partition(_expc(s)) # mantissa, exponent, +/-power
return m + e + p[0] + _pad0(p[1:], n)
def _efmt(x, n, e): # returns formatted float x: n decimals, 'e'/'E'
return ('{0:.' + str(n) + e + '}').format(x)
x = x if isinstance(x, float) else float('nan')
nmax = 16 if not isinstance(nmax, int) else max(0, nmax)
n = 6 if not isinstance(n, int) else min(max(0, n), nmax)
m = 2 if not isinstance(m, int) else max(0, m)
e = 'e' if e not in {'E', 'e'} else e
return _efmtes(_efmt(x, n, e), m)
Examples:
>>> efmte(42., n=1, m=5)
'4.2e+00001'
>>> efmte('a')
'-1.#IND00e+00'
>>> # Yuck: I was expecting 'nan'. Anyone else?
>>> from math import pi
>>> efmte(pi)
'3.141593e+00'
>>> efmte(pi, m=3)
'3.141593e+000'