pythonformatting

Scientific notation without plus sign


The '{:e}'.format function prints positive values in the form "1e+06".

Is there some other format which instead displays it as "1e6" (and negative exponents obviously as "1e-6")?

Or would a custom format function be necessary?


Solution

  • You could derive your own string.Formatter subclass:

    import string
    
    
    class MyFormatter(string.Formatter):
        def format_field(self, value, format_spec):
            if format_spec == 'm':
                return super().format_field(value, 'e').replace('e+', 'e')
            else:
                return super().format_field(value, format_spec)
    
    
    fmt = MyFormatter()
    v = 1e+06
    print(fmt.format('{:e}, {:m}', v, v))  # -> 1.000000e+06, 1.000000e06