[Python-ideas] Have a "j" format option for lists

Eric V. Smith eric at trueblade.com
Wed May 9 09:49:12 EDT 2018


On 5/9/18 9:28 AM, Chris Angelico wrote:
> On Wed, May 9, 2018 at 11:06 PM, Steven D'Aprano <steve at pearwood.info> wrote:
>> On Wed, May 09, 2018 at 09:39:08AM -0300, Facundo Batista wrote:
>>> This way, I could do:
>>>
>>>>>> authors = ["John", "Mary", "Estela"]
>>>>>> "Authors: {:, j}".format(authors)
>>> 'Authors: John, Mary, Estela'
>>
>>
>>
>> Looks interesting, but I think we need to know the semantics in more
>> detail. For example:
>>
>> - if the items of the list aren't already strings, how are they
>>   converted?
>
> I'd expect that they'd be converted using format(), which by default
> would just call str(). How you'd go about specifying a format string,
> though, I'm not sure.
>
>> - do you truly mean lists *only*, or is any iterable acceptible?
>
> With the letter being "j" and the semantics being lifted from
> str.join(), I would guess the latter.

Since '{:spec}'.format(obj) basically becomes obj.__format__('spec'), 
this would have to be implemented on a concrete type (in the above 
example, list).

> From the sound of it, this would be a change made to format(), or
> rather the underlying C level function, PyObject_Format(). If done
> there, it would also automatically apply to f-strings and anything
> else that calls format(). Perhaps the right way is not a colon marker,
> but an enhancement to the ! notation? We currently have !s and !r to
> do str() and repr(), and this could be !j followed by a join string.
> Combining this with a colon would allow the individual elements to be
> formatted with the given string, and then joined. For instance:

I would object to changing the format machinery. Any format spec should 
be interpreted by some object's __format__ method.

Eric

> x = [1,2,3]
> msg = '#{x:3d!j, }#'.format(x=x)
> # or equivalently
> msg = f'#{x:3d!j, }#'
> assert msg == '#  1,   2,   3#'
>
> +0.5 on this. I don't currently yearn for it, but I'd probably use it
> if it were available.
>
> ChrisA
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>


More information about the Python-ideas mailing list