arkadiy
arkadiy

Reputation: 766

What is the best way to print a list on one line with separators?

I am attempting to iterate over a list of strings and print them in one line, using "," as separators. However, contrary to the documentation, the print() function seems to ignore the separator and print the items as if the sep was not included. The code, along with the results, if below:

brothers = ['Larry', 'Harry', 'David']

for brother in brothers: 
    print(brother, sep=', ', end='\n')

Larry
Harry
David

Expected Result: Larry, Harry, David

Upvotes: 1

Views: 683

Answers (3)

Shoonya
Shoonya

Reputation: 128

You have to provide all the values in the same call. This will work:

brothers = ['Larry', 'Harry', 'David']
print(*brothers, sep=', ', end='\n')

Quoting from https://docs.python.org/3/library/functions.html#print "Print objects to the text stream file"

Upvotes: 1

wim
wim

Reputation: 363384

You were close:

>>> print(*brothers, sep=', ', end='\n')
Larry, Harry, David

Upvotes: 1

DaLynX
DaLynX

Reputation: 338

You're looking for join:

print ", ".join(brothers)

Upvotes: 0

Related Questions