formatting list -> comma separated (slightly different)

Larry Bates larry.bates at websafe.com`
Wed Jul 9 23:02:42 CEST 2008


Michiel Overtoom 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?
> 
> Greetings,
> 
> 
> '''
> Formatting a sequence of items such that they are separated by
> commas, except the last item, which is separated by the word 'and'.
> 
> Used for making lists of dates and items more human-readable
> in generated emails and webpages.
> 
> For example:
> 
> Four friends have a dinner: Anne, Bob, Chris and Debbie
> Three friends have a dinner: Anne, Bob and Chris
> Two friends have a dinner: Anne and Bob
> One friend has a dinner: Anne
> No friend has a dinner:
> 
>      ['Anne','Bob','Chris','Debbie'] -> "Anne, Bob, Chris and Debbie"
>      ['Bob','Chris','Debbie'] -> "Bob, Chris and Debbie"
>      ['Chris','Debbie'] -> "Chris and Debbie"
>      ['Debbie'] -> "Debbie"
>      [] -> ""
> 
> '''
> 
> 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
> 
> friends=['Anne','Bob','Chris','Debbie','Eve','Fred']
> while True:
>     print friends,'->',pretty(friends)
>     if friends:
>         friends.pop(0)
>     else:
>         break
> 
> 
> 
> 
> 
IMHO slightly easier to read and faster if the lists are long:

def pretty(f):
     if len(f) == 0 :
         return ""
     elif len(f) == 1:
         return f[0]
     else:
         return ', '.join(f[:-1]) + ' and ' + f[-1]


-Larry



More information about the Python-list mailing list