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

MRAB python at mrabarnett.plus.com
Thu Dec 15 12:27:14 EST 2011


On 15/12/2011 16: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.

How about this:

def and_list(items):
     if len(items) <= 2:
         return " and ".join(items)

     return ", ".join(items[ : -1]) + ", and " + items[-1]

print(and_list([]))
print(and_list(['a']))
print(and_list(['a', 'b']))
print(and_list(['a', 'b', 'c']))
print(and_list(['a', 'b', 'c', 'd']))



More information about the Python-list mailing list