On 12/15/2011 12:27 PM, MRAB wrote:
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]

To avoid making a slice copy,

  last = items.pop()
  return ", ".join(items) + (", and " + last)

I parenthesized the last two small items to avoid copying the long string twice with two appends. Even better is

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

so the entire output is created in one operation with no copy.

But I would only mutate the list if I started with
  items = list(iterable)
where iterable was the input, so I was mutating a private copy.

--
Terry Jan Reedy

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to