子类string.Formatter

Cam*_*ium 5 python string stringtemplate

在这里发表评论:如何定义一个新的字符串格式化程序,我尝试了子类化string.Formatter.这就是我所做的.不幸的是,我似乎在这个过程中打破了它

import string
from math import floor, log10

class CustFormatter(string.Formatter):
    "Defines special formatting"
    def __init__(self):
        super(CustFormatter, self).__init__()

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

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

    def format_field(self, value, format_string):
      # handle an invalid format
      if format_string == "i":
          return self.eng(value)
      else:
          return super(CustFormatter,self).format_field(value, format_string)

fmt = CustFormatter()
print('{}'.format(0.055412))
print(fmt.format("{0:i} ", 55654654231654))
print(fmt.format("{} ", 0.00254641))
Run Code Online (Sandbox Code Playgroud)

好像在最后一行,我没有按位置引用变量,我得到了一个KeyError.很显然,期望一把钥匙在原班上是可选的,但我不明白为什么,我不确定我做错了什么.

fal*_*tru 5

str.format 会自动编号,而string.Formatter不会。

修改__init__和覆盖get_value可以解决问题。

def __init__(self):
    super(CustFormatter, self).__init__()
    self.last_number = 0

def get_value(self, key, args, kwargs):
    if key == '':
        key = self.last_number
        self.last_number += 1
    return super(CustFormatter, self).get_value(key, args, kwargs)
Run Code Online (Sandbox Code Playgroud)

顺便说一句,上面的代码并没有严格模仿str.format行为。str.format如果我们将自动编号与手动编号混合,则会抱怨,但上面没有。

>>> '{} {1}'.format(1, 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: cannot switch from automatic field numbering to manual field specification
>>> '{0} {}'.format(1, 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: cannot switch from manual field specification to automatic field numbering
Run Code Online (Sandbox Code Playgroud)