16

我的代码遍历一组并打印演员的名字:

for actor in actorsByMovies():
    print actor+",",

结果如下所示:

Brad Pitt, George Clooney,

但我希望它检测到最后一个元素,这样它就不会打印最后一个逗号。结果应该是:

Brad Pitt, George Clooney

我怎样才能做到这一点?

4

3 回答 3

29
print(', '.join(actorsByMovies()))
于 2013-05-02T12:53:03.160 回答
3

@jamylak 的解决方案是最好的,只要你可以使用它,但如果你必须为其他事情保留循环,你可能会做这样的事情:

from __future__ import print_function # Python [2.6, 3)

for index, actor in enumerate(actorsByMovies()):
    if index > 0:
        print(', ', end='')
    print(actor, end='')

使用相同的新print功能,您可以这样做而不是使用str.join

print(*actorsByMovies(), sep=', ')
于 2013-05-02T13:05:45.903 回答
0

#我们可以直接在for循环中使用这个方法。

 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.
   
       
于 2021-03-06T08:00:55.263 回答