user88720
user88720

Reputation: 342

How to print multiple items in a list as a string?

I have a list called combined with many items. I would like to print the first three items as a string, each all on a new line. If I type:

print str(combined[0]) 

;it will print the first item out as as string, without being inside [''].

However if I try to do the same with the first three by using:

print str(combined[0:3]) 

;it prints the first three items, but still in a list.

How can I get these three items of the list to print out as strings with each on a new line?

Upvotes: 0

Views: 4333

Answers (1)

randomir
randomir

Reputation: 18687

Try:

print "\n".join(combined[0:3])

From the Python docs:

str.join(iterable)

Return a string which is the concatenation of the strings in the iterable iterable. The separator between elements is the string providing this method.

If your list combined contains non-strings, you might first want to convert them to strings (e.g. with map(str, ...):

print "\n".join(map(str, combined[0:3]))

Upvotes: 1

Related Questions