PEP 378: Format Specifier for Thousands Separator

nn pruebauno at latinmail.com
Fri May 24 09:50:51 EDT 2013


On May 23, 2:42 pm, Dave Angel <da... at davea.name> wrote:
> On 05/23/2013 11:26 AM, Carlos Nepomuceno wrote:
>
> > ----------------------------------------
> >> Date: Thu, 23 May 2013 06:44:05 -0700
> >> Subject: Re: PEP 378: Format Specifier for Thousands Separator
> >> From: prueba... at latinmail.com
> >> To: python-l... at python.org
> > [...]
>
> You left out the part where a and f are initialized:
>
>  >>> a='%s'
>  >>> f=(3,5)
>
> >>>>> eggs(a,f)
> >> Traceback (most recent call last):
> >> File "<pyshell#29>", line 1, in <module>
> >> eggs(a,f)
> >> File "<pyshell#1>", line 1, in eggs
> >> def eggs(spam, ham): return spam % ham
> >> TypeError: not all arguments converted during string formatting
> >>>>> '%s'%(5%3)
> >> '2'
>
> > So % doesn't handle tuples! Why's that? Is it intentional (by design)?
>
> It's a conflict in the design.  A tuple is used to supply multiple
> arguments to the % operator.  So if you want to have a tuple as the
> first argument, you need to enclose it in another tuple.
>
> try the following:
>
> print a % (f,)
>
> The trouble is, it doesn't generalize very readily, so it's difficult to
> use in a function like eggs()
>
> --
> DaveA

It's all there, it's just that quoting ate it. Let's try this again:

>>> def eggs(spam, ham): return spam % ham
>>> def milk(beef, steak): return beef.format(steak)
>>> a='%s'
>>> c=9
>>> d=4
>>> e=[1,2]
>>> f=(3,5)
>>> d='{}'
>>> eggs(a,4)
'4'
>>> eggs(c,4)
1
>>> eggs(a,e)
'[1, 2]'
>>> eggs(a,f)

Traceback (most recent call last):
  File "<pyshell#29>", line 1, in <module>
    eggs(a,f)
  File "<pyshell#1>", line 1, in eggs
    def eggs(spam, ham): return spam % ham
TypeError: not all arguments converted during string formatting
>>> '%s'%(5%3)
'2'

>>> milk(d,4)
'4'
>>> milk(c,4)

Traceback (most recent call last):
  File "<pyshell#53>", line 1, in <module>
    milk(c,4)
  File "<pyshell#49>", line 1, in milk
    def milk(beef, steak): return beef.format(steak)
AttributeError: 'int' object has no attribute 'format'
>>> milk(d,e)
'[1, 2]'
>>> milk(d,f)
'(3, 5)'
>>> '{}'.format(5%3)
'2'

The three issues represented:
1. Functions in which both values of the operator are parameters might
not return a string but an integer instead. It is not always
immediately obvious when reading such functions if modulus or
formatting is intended.
2. Function doesn't handle tuple properly unless carefully written
3. Too much % noise because % is used for 3 things: the special
placeholder character inside format strings, the format operator and
the modulus operator.



More information about the Python-list mailing list