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

Roy Smith roy at panix.com
Thu Dec 15 14:01:14 EST 2011


FWIW, I ended up with:

        n = len(names)
        if n == 0:
            return ''
        if n == 1:
            return names[0]
        pre = ', '.join(names[:-1])
        post = names[-1]
        return '%s, and %s' (pre, post)

the slice-and-join() takes care of both the 2 and >2 element cases at the same time :)

It would be nice if there were some standard way to do this.  I'm sure I've seen something that was essentially a join() that took two delimiters; one for most elements, the other a special-case for the last one.  I can't remember where I saw it.  I'm guessing in some web framework.



More information about the Python-list mailing list