Python2.7 string.format()中的逗号和字符串

2024-05-09 23:37:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我对以下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相同”,而是检查正在格式化的对象的类型?


Tags: 字符串formatdocs类型格式with运算符细节
2条回答

参考PEP 378 -- Format Specifier for Thousands Separator

The ',' option is defined as shown above for types 'd', 'e', 'f', 'g', 'E', 'G', '%', 'F' and ''. To allow future extensions, it is undefined for other types: binary, octal, hex, character, etc

在您的示例中,您没有与字符串表示类型交互;而是与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'

相关问题 更多 >