Newbie: last item of a loop

Bengt Richter bokr at oz.net
Fri May 2 23:01:12 EDT 2003


On Fri, 02 May 2003 14:38:09 +0200, Sven Brandt <sven_NOSPAM at manastar.de> wrote:

>Hi Anton,
>
>to be more precise:
>
>I have a list of names which I want as a joined string, seperated by 
>kommas except for the last item which is seperated by 'and'. ['Peter', 
>'Paul','Mary'] -> 'Peter, Paul and Mary'
>
>here is what I tried (I know that the 'i.index' does not give me the 
>index-number of the sequence item, but I don't know better. Sorry. But I 
>hope you get the point ...) :
>
>my_names=['Peter', 'Paul','Mary']
>my_name_string=''
>
>for i in my_names:
>   # if more than one name
>   if len(driver_names) > 1:
>     # if not last or second-last name append komma
>     if i.index  < len(driver_names) - 1:
>       driver_names_string = driver_names_string + ', '
>     # if second-last append 'and'
>     if i.index  == len(driver_names) - 1:
>       driver_names_string = driver_names_string + ' und '
>
You could do it with a one-liner ;-)

    my_name_string = ' and '.join(filter(None, [', '.join(my_names[:-1]), my_names[-1]]))

as in
 >>> my_names=['Peter', 'Paul','Mary']
 >>> while my_names:
 ...     print ' and '.join(filter(None, [', '.join(my_names[:-1]), my_names[-1]]))
 ...     my_names = my_names[:-1]
 ...
 Peter, Paul and Mary
 Peter and Paul
 Peter

Regards,
Bengt Richter




More information about the Python-list mailing list