gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:29:38 25 4
gpt4 key购买 nike

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

最佳答案

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

关于python - Python 2.7 中的逗号和字符串 string.format(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15730959/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com