How to generate "a, b, c, and d"?

Ethan Furman ethan at stoneleaf.us
Thu Dec 15 13:19:51 EST 2011


Tim Chase wrote:
> On 12/15/11 10:48, Roy Smith wrote:
>> I've got a list, ['a', 'b', 'c', 'd'].  I want to generate the string, 
>> "a, b, c, and d" (I'll settle for no comma after 'c').  Is there some 
>> standard way to do this, handling all the special cases?
>>
>> [] ==>  ''
>> ['a'] ==>  'a'
>> ['a', 'b'] ==>  'a and b'
>> ['a', 'b', 'c', 'd'] ==>  'a, b, and c'
>>
>> It seems like the kind of thing django.contrib.humanize would handle, 
>> but alas, it doesn't.
> 
> If you have a list, it's pretty easy as MRAB suggests.  For arbitrary 
> iterators, it's a bit more complex.  Especially with the odd edge-case 
> of 2 items where there's no comma before the conjunction (where >2 has 
> the comma before the conjunction).  If you were willing to forgo the 
> Oxford comma, it would tidy up the code a bit.  Sample code below

<snip>

Why go through all that instead of just converting the iterator into a 
list at the beginning of MRAB's solution and then running with it?

~Ethan~



More information about the Python-list mailing list