formatting list -> comma separated (slightly different)

Niklas Norrthon niklas.norrthon at hotmail.com
Tue Jul 22 02:32:06 EDT 2008


On 9 Juli, 22:25, Michiel Overtoom <mot... at xs4all.nl> wrote:
> Paul & Robert wrote...
> > d = ["soep", "reeds", "ook"]
> >print ', '.join(d)
> > soep, reeds, ook
>
> I occasionally have a need for printing lists of items too, but in the form:
> "Butter, Cheese, Nuts and Bolts".  The last separator is the word 'and'
> instead of the comma. The clearest I could come up with in Python is below.
> I wonder if there is a more pythonic solution for this problem.  Maybe
> something recursive?

[snip]

> def pretty(f):
>     if len(f)==0: return ''
>     if len(f)==1: return f[0]
>     sepwithcommas=f[:-1]
>     sepwithand=f[-1]
>     s=', '.join(sepwithcommas)
>     if sepwithand:
>         s+=' and '+sepwithand
>     return s

def pretty(names):
    return ' and '.join(', '.join(names).rsplit(', ', 1))


> friends=['Anne','Bob','Chris','Debbie','Eve','Fred']

print pretty(friends)



More information about the Python-list mailing list