Newbie: last item of a loop
Cecil H. Whitley
cwhitley at earthlink.net
Fri May 2 23:59:39 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'
> >
*snip*
Here is my solution:
names = ["a","b","c"]
if len(names)>1:
lines = ", ".join(names[0:len(names)-1])
lines = lines + " and " + names[len(names)-1]
else:
lines = names[0]
print lines
In this case names cannot be an empty list. Extending the else to
else if len(names)==1: see above
else: lines = ""
would even handle that case. I ran this code through test cases of 1, 2,
and 3 names. Any logic errors?
Cecil
More information about the Python-list
mailing list