Format specification mini-language for list joining

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Nov 10 11:55:29 EST 2012


On Sat, 10 Nov 2012 02:26:28 -0800, Tobia Conforto wrote:

> Hello
> 
> Lately I have been writing a lot of list join() operations variously
> including (and included in) string format() operations.
> 
> For example:
> 
>   temps = [24.369, 24.550, 26.807, 27.531, 28.752]
> 
>   out = 'Temperatures: {0} Celsius'.format(
>             ', '.join('{0:.1f}'.format(t) for t in temps)
>         )
> 
>   # => 'Temperatures: 24.4, 24.6, 26.8, 27.5, 28.8 Celsius'
> 
> This is just a simple example, my actual code has many more join and
> format operations, split into local variables as needed for clarity.

Good plan! But then you suggest:


> Here is what I came up with:
>   out = 'Temperatures: {0:", ":.1f} Celsius'.format(temps)
>   # => 'Temperatures: 24.4, 24.6, 26.8, 27.5, 28.8 Celsius'
> 
> Here ", " is the joiner between the items and <.1f> is the format string
> for each item.

And there goes all the clarity.

Is saving a few words of Python code so important that you would prefer 
to read and write an overly-terse, cryptic mini-language?

If you're worried about code re-use, write a simple helper function:

def format_items(format, items):
    template = '{0:%s}' % format
    return ', '.join(template.format(item) for item in items)

out = 'Temperatures: {0} Celsius'.format( format_items('.1f, temps) )



-- 
Steven



More information about the Python-list mailing list