Skip to content Skip to sidebar Skip to footer

How To Define A New String Formatter

I often use this small function eng(x) especially to show big or small numbers in an easy to read way. This allows me to write'%e' % (number). I would like to be able to write '%n'

Solution 1:

You can implement a new number class:

from math import floor, log10
classsnumber(float):
        defpowerise10(x):
            if x == 0: return0 , 0 
            Neg = x <0if Neg : x = -x
            a = 1.0 * x / 10**(floor(log10(x)))
            b = int(floor(log10(x)))
            if Neg : a = -a
            return a ,b

        def__str__(x):
            a , b = snumber.powerise10(x)
            if -3<b<3: return"%.4g" % x 
            a = a * 10**(b%3)
            b = b - b%3return"%.4g*10^%s" %(a,b)

print"{}".format(snumber(100000))

Gives:

100*10^3

Solution 2:

After further research, I have found how to subclass string.Formatter as per @bereal's suggestion.

import string
from math import floor, log10

classCustFormatter(string.Formatter):
    "Defines special formatting"def__init__(self):
        super(CustFormatter, self).__init__()

    defpowerise10(self, x):
        if x == 0: return0, 0
        Neg = x < 0if Neg: x = -x
        a = 1.0 * x / 10**(floor(log10(x)))
        b = int(floor(log10(x)))
        if Neg: a = -a
        return a, b

    defeng(self, x):
        a, b = self.powerise10(x)
        if -3 < b < 3: return"%.4g" % x
        a = a * 10**(b%3)
        b = b - b%3return"%.4g*10^%s" % (a, b)

    defformat_field(self, value, format_string):
      # handle an invalid formatif format_string == "i":
          return self.eng(value)
      else:
          returnsuper(CustFormatter,self).format_field(value, format_string)

fmt = CustFormatter()
print('{}'.format(0.055412))
print(fmt.format("{0:i} ", 55654654231654))
print(fmt.format("{} ", 0.00254641))

The only problem is that I have partially broken it as for the last line if I don't refer to the variables by position, I get a KeyError.

Post a Comment for "How To Define A New String Formatter"