Commas and strings in Python 2.7 string.format ()

I am confused by the following behavior of Python 2.7 and Python 3.3 in string formatting. This is a question related to the detailed question of how the comma operator interacts with string types.

>>> 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'.

What bothers me, why does the option work ,that does not have an explicit type of string representation. docs say that if you omit the type, it is "Same as s". And yet here he acts differently than s.

I would throw it as an argument against wrinkles / angles, but this syntax is used as an example in the documents '{:,}'.format(1234567890). Are there other "special" behaviors hidden in Python when the string representation type is omitted? Maybe instead of “the same as s”, what the code really does is to check the type of the formatted thing?

+5
source share
2 answers

In your example, you are not interacting with string representation types; you interact with types int. Objects can provide their own formatting behavior by defining a method __format__. As noted in 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'
+2

PEP 378 - Thousands Separator

',' 'd', 'e', ​​'f', 'g', 'E', 'G', '%', 'F' ''. , undefined : , , , ..

0

All Articles