Emma
Emma

Reputation: 85

Can I include a for loop inside my print statement?

I have a list of winners of an event. I want to print them out at the end of my code, minus the brackets and quotes, and I am currently using:

            for items in winners:
                print(items)

Can I include this in a print statement? I want:

            print("The winners of {} were: {} with a score of {}".format(sport, winners, max_result))

Is there a way of integrating the for loop into the print statement, or another way of eliminating the quotes and square brackets such that I can include it in the statement?

Thanks.

Upvotes: 3

Views: 7052

Answers (4)

godaygo
godaygo

Reputation: 2288

First note, in Python 3 print is a function, but it was a statement in Python 2. Also you can't use a for statement as an argument. Only such weird solution comes to my mind, which only looks like a for loop:

data = ['Hockey','Swiss', '3']
print("Sport is {}, winner is {}, score is {}".format(*( _ for _ in data )))

Of course, because print is a function, you can write your own function with all stuff you need, as an example:

def my_print(pattern, *data):
    print(pattern.format(*( _ for _ in data)))  

my_print("Sport is {}, winner is {}, score is {}", 'Hockey', 'Swiss', '3')

You can also read about f-strings "Literal String Interpolation" PEP 498, which will be introduced in Python 3.6. This f-strings will provide a way to embed expressions inside string literals, using a minimal syntax.

Upvotes: 0

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160637

A for loop can only be supplied to print in the form of a comprehension.

But, if the list contents are in the respective order you require you can simply do:

print("The winners of {} were: {} with a score of {}".format(*winners))

This just matches each bracket with each item in the list. If you need to order this differently you just supply their relative position:

print("The winners of {1} were: {0} with a score of {2}".format(*winners))

Upvotes: 0

Soviut
Soviut

Reputation: 91615

You can't include a for loop but you can join your list of winners into a string.

winners = ['Foo', 'Bar', 'Baz']
print('the winners were {}.'.format(', '.join(winners)))

This would print

the winners were Foo, Bar, Baz.

Upvotes: 6

zvone
zvone

Reputation: 19382

If winners is a list of strings, you can concatenate them using str.join.

For example:

>>> winners = ['John', 'Jack', 'Jill']
>>> ', '.join(winners)
'John, Jack, Jill'

So you can put ', '.join(winners) in your print call instead of winners and it will print the winners separated by commas.

Upvotes: 0

Related Questions