【问题标题】:How to provide custom formatting from format string?如何从格式字符串提供自定义格式?
【发布时间】:2019-12-25 10:59:00
【问题描述】:

我可以使用自定义类来扩展 Python 的字符串格式:

class CaseStr(str):
    def __format__(self, fmt):
        if fmt.endswith('u'):
            s = self.upper()
            fmt = fmt[:-1]
        elif fmt.endswith('l'):
            s = self.lower()
            fmt = fmt[:-1]
        else:
            s = str(self)
        return s.__format__(fmt)

然后我可以使用这个类来格式化传递给字符串格式方法的参数:

unformatted_string = 'uppercase: {s:u}, lowercase: {s:l}'
print unformatted_string.format(s=CaseStr('abc'))

虽然这可行,但自定义格式说明符位于基本字符串中似乎很尴尬,但传递给它的格式方法的参数实际上负责解析格式说明符。

有没有办法将解释自定义字符串所需的知识放入基本字符串本身?

class CaseStrWrapper(str):
    ...

unformatted_string = CaseStrWrapper('uppercase: {s:u}, lowercase: {s:l}')
print unformatted_string.format(s='abc')

【问题讨论】:

  • 您可以重载格式,但格式说明符的理解是要格式化的事情的工作,而不是str 的工作。这很像每种类型都有自己的__str__ 方法,而不是试图让str 类知道如何对每种类型的对象进行字符串化。
  • 为什么不直接使用格式字符串呢?例如f"{s.upper()} {s.lower()}"?
  • 听起来像str.format以外的格式化工具更适合你想做的事情。
  • @SamMason 我正在使用 Python 2.7。

标签: python string format


【解决方案1】:

您通常会为此使用custom string formatting(请参阅PEP 3101)。对于你的情况,你可以有这样的东西:

import string

class MyFormatter(string.Formatter):
    def format_field(self, value, format_spec):
        if isinstance(value, str):
            if format_spec.endswith('u'):
                value = value.upper()
                format_spec = format_spec[:-1]
            elif format_spec.endswith('l'):
                value = value.lower()
                format_spec = format_spec[:-1]
        return super(MyFormatter, self).format(value, format_spec)

fmt = MyFormatter()
print(fmt.format('uppercase: {s:u}, lowercase: {s:l}', s='abc'))
# uppercase: ABC, lowercase: abc

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-28
    • 1970-01-01
    • 2019-02-16
    • 2013-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-09
    相关资源
    最近更新 更多