[Python-ideas] Have a "j" format option for lists
Steven D'Aprano
steve at pearwood.info
Wed May 9 09:06:10 EDT 2018
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?
- do you truly mean lists *only*, or is any iterable acceptible?
Here's a tiny proof-of-concept for the feature:
import string
class Template(string.Formatter):
def format_field(self, value, spec):
if spec.endswith('j'):
value = ', '.join(map(str, value))
spec = spec[:-1] + 's'
return super(Template, self).format_field(value, spec)
Template().format('{:j} => {:d}', ['alpha', 'beta', 42, 'delta'], 99)
# returns 'alpha, beta, 42, delta => 99'
--
Steve
More information about the Python-ideas
mailing list