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?
print(', '.join(actorsByMovies()))
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=', ')
#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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.