Reputation: 9643
My code iterates over a set and print actor's names:
for actor in actorsByMovies():
print actor+",",
The result looks like:
Brad Pitt, George Clooney,
But I want it to detect the last element so that it won't print the last comma. The result should be instead:
Brad Pitt, George Clooney
How can I do that?
Upvotes: 18
Views: 15587
Reputation: 1
#we can directly use this method in for loop.
x=''
y='' #some empty string we want to concatenate(add) the list strings to.
for iterator in list: #Some list we will be parsing.
x = x + iterator # adding value to string available.
x=x +', ' # adding , and space
y= x[:-2] # as string is immutable adding value of x in y without comma.
return y # it will return the desired output.
Upvotes: 0
Reputation: 6616
The solution by @jamylak is best whenever you can use it, but if you have to keep the loop for other things, you might do something like this:
from __future__ import print_function # Python [2.6, 3)
for index, actor in enumerate(actorsByMovies()):
if index > 0:
print(', ', end='')
print(actor, end='')
Using the same new print
function, you could do this instead of using str.join
:
print(*actorsByMovies(), sep=', ')
Upvotes: 6