Newbie: last item of a loop

Jørgen Cederberg jorgencederberg at hotmail.com
Fri May 2 08:50:26 EDT 2003


Sven Brandt 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 '
> 
>> l = ['a', 'b', 'c', 'd']
>>
>> # process l[0]
>> for e in l[1:-1]:
>>     # process inner elements
>> # process l[-1]
> 
> 
> This would do but I prefere to have it in one loop for better readability.
> 
Hi Sven

You could rewrite this to:

my_names=['Peter', 'Paul','Mary']
if len(my_names) > 1:
     my_name_string = ', '.join(my_names[:-1]) + ' and ' + my_names[-1]
else:
     my_name_string = my_names[0]

I hope you can understand the usage of the join method on string.

Regards
Jorgen Cederberg





More information about the Python-list mailing list