代码之家  ›  专栏  ›  技术社区  ›  Nelson

Python 2.7 string.format()中的逗号和字符串

  •  4
  • Nelson  · 技术社区  · 13 年前

    我对以下Python 2.7和Python 3.3在字符串格式中的行为感到困惑。这是一个关于逗号运算符如何与字符串表示类型交互的细节问题。

    >>> format(10000, ",d")
    '10,000'
    >>> format(10000, ",")
    '10,000'
    >>> format(10000, ",s")
    ValueError: Cannot specify ',' with 's'.
    
    >>> "{:,}".format(10000)
    '10,000'
    >>> "{:,s}".format(10000)
    ValueError: Cannot specify ',' with 's'.
    

    让我困惑的是为什么 , 变体有效,即没有显式字符串表示类型的变体。这个 docs 说如果你省略了类型,它是“与 s 。”然而,在这里,它的行为与 s .

    我认为这只是一个褶皱/角落的情况,但在文档中使用了以下语法作为示例: '{:,}'.format(1234567890) 。当省略字符串表示类型时,Python中是否隐藏了其他“特殊”行为?也许代码真正做的不是“与s相同”,而是检查被格式化的东西的类型?

    2 回复  |  直到 13 年前
        1
  •  3
  •   Ned Deily    13 年前

    在您的示例中,您没有与字符串表示类型进行交互;您正在与交互 int 演示类型。对象可以通过定义 __format__ 方法如政治公众人物3101所述:

    The new, global built-in function 'format' simply calls this special
    method, similar to how len() and str() simply call their respective
    special methods:
    
        def format(value, format_spec):
            return value.__format__(format_spec)
    
    Several built-in types, including 'str', 'int', 'float', and 'object'
    define __format__ methods.  This means that if you derive from any of
    those types, your class will know how to format itself.
    

    演示文稿类型 s 可以理解的是 整数 对象(请参见每个对象类型的文档化表示类型列表 here ). 异常消息有些误导性。没有 , ,问题更清楚了:

    >>> format(10000, "s")
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: Unknown format code 's' for object of type 'int'
    
        2
  •  0
  •   Abhijit    13 年前

    参考 PEP 378 -- Format Specifier for Thousands Separator

    如上所示,为类型“d”、“e”、“f”、“g”定义了“,”选项, “E”、“G”、“%”、“F”和“”。为了允许未来的扩展,它是未定义的 用于其他类型:二进制、八进制、十六进制、字符等