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

Chris Angelico rosuav at gmail.com
Wed May 9 09:28:41 EDT 2018

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.

>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:

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.


More information about the Python-ideas mailing list