繁体   English   中英

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

[英]Commas and strings in Python 2.7 string.format()

我对String格式化中的以下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'.

令我困惑的是,为什么,变体工作,没有明确的字符串表示类型。 文档说如果省略类型,那就是“和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对象(见每个对象类型文件介绍类型列表在这里 )。 异常消息有点误导。 没有,问题就更清楚了:

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

请参阅PEP 378 - 千位分隔符的格式说明符

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM