Single format descriptor for list

Jussi Piitulainen jussi.piitulainen at helsinki.fi
Wed Jan 20 06:40:40 EST 2016


"Frank Millman" writes:

> "Paul Appleby"  wrote in message
> news:pan.2016.01.20.09.35.09 at nowhere.invalid...
>>
>> 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?
>>
>
> How about this -
>
>>>> a = range(4, 8)
>>>> print('\n'.join(['{}th'.format(x) for x in a]))
> 4th
> 5th
> 6th
> 7th
>>>>

Or this:

>>> print(*map('{}th'.format, range(8)), sep = '\n')
0th
1th
2th
3th
4th
5th
6th
7th

But a separate named function to format an individual number seems like
a good idea, because 1st, 2nd, and 3rd.



More information about the Python-list mailing list