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

时间:2013-03-31 15:24:02

标签: python string-formatting

我对字符串格式化中的以下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 个答案:

答案 0 :(得分:2)

在您的示例中,您没有与字符串表示类型进行交互;您正在与int演示文稿类型进行交互。对象可以通过定义__format__方法来提供自己的格式化行为。如PEP 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可以理解为int个对象无法实现(请参阅每个对象类型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'

答案 1 :(得分:0)

参考PEP 378 -- Format Specifier for Thousands Separator

  

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

相关问题