简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM