【问题标题】:Scientific notation without plus sign不带加号的科学记数法
【发布时间】:2019-07-11 19:44:13
【问题描述】:

'{:e}'.format 函数以“1e+06”的形式打印正值。

是否有其他格式将其显示为“1e6”(负指数显然为“1e-6”)?

或者是否需要自定义格式功能?

【问题讨论】:

    标签: python formatting


    【解决方案1】:

    您可以派生自己的string.Formatter 子类:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-04
      • 1970-01-01
      相关资源
      最近更新 更多