Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to not print comma in last element in a for loop?

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?

like image 865
Tom Avatar asked May 02 '13 12:05

Tom


People also ask

How do you remove the comma at the end of a for loop in python?

You can use ', '.

How do you remove the last comma in a for loop?

An alternative method of removing the comma from last foreach loop item. In this alternative way, we are going to use the PHP array_push() function. below is the code: <?

How do you end a comma in python?

Python 3 changes this completely and the trailing comma is no longer accepted. You use the end parameter to change the line ending, setting it to a blank string to get the same effect. More like a necessary consequence.


1 Answers

print(', '.join(actorsByMovies()))
like image 183
jamylak Avatar answered Sep 22 '22 22:09

jamylak