Single format descriptor for list

Chris Angelico rosuav at gmail.com
Wed Jan 20 05:16:57 EST 2016


On Wed, Jan 20, 2016 at 8:35 PM, Paul Appleby <pap at nowhere.invalid> wrote:
> In BASH, I can have a single format descriptor for a list:
>
> $ a='4 5 6 7'
> $ printf "%sth\n" $a
> 4th
> 5th
> 6th
> 7th
>
> Is this not possible in Python? Using "join" rather than "format" still
> doesn't quite do the job:
>
>>>> a = range(4, 8)
>>>> print ('th\n'.join(map(str,a)))
> 4th
> 5th
> 6th
> 7
>
> Is there an elegant way to print-format an arbitrary length list?

Python's string formatting is fairly rich, but not quite that rich.
I'd probably just loop over the range and print them separately:

>>> a = range(4, 8)
>>> for n in a:
...     print("%sth" % n)
...
4th
5th
6th
7th

Maybe Python could grow a %{ ... %} marker like Pike's?

> array a = enumerate(4,1,4);
> write("%{%dth\n%}", a);
4th
5th
6th
7th

The semantics are simply recursive - the printf string inside the
markers is evaluated once for each element of the provided sequence
(iterable), and the results concatenated.

ChrisA



More information about the Python-list mailing list