如何在python中进行for循环输出?

时间:2013-12-27 04:15:04

标签: python for-loop printing output

输出本身正在工作,但我如何使用for循环外部格式化输出或将其写入变量或数组?

...
for item in soup.findAll('span', {"itemprop":"actor"}):
    print item.text
...

输出示例:

Sylvester Stallone
Arnold Schwarzenegger

但输出应该类似于:

Actors: Sylvester Stallone, Arnold Schwarzenegger

3 个答案:

答案 0 :(得分:2)

actor_list = soup.findAll('span', {"itemprop":"actor"})
print "Actors: {0}".format(", ".join(actor_list))

答案 1 :(得分:1)

你可以做的一件事是......

actors = [item.text for item in soup.findAll('span', {"itemprop":"actor"})]
print "Actors: %s" % (", ".join(actors))

答案 2 :(得分:0)

不将其保存到变量:

print "Actors: ",
...
for item in soup.findAll('span', {"itemprop":"actor"}):
    print item.text, ",",
...