kmario23
kmario23

Reputation: 61305

Unable to print a list using join

The following code throws an error.

squares = map(lambda a: a*a, [1,2,3,4,5])  
print "%d." %", ".join(squares)

How should I print it join? I want the result to be as 1, 4, 9, 16, 25.

Upvotes: 0

Views: 86

Answers (1)

zhangxaochen
zhangxaochen

Reputation: 33997

Change

print "%d." %", ".join(squares)

to

print ", ".join(map(str, squares))

If you want to append a . to the end of line, use:

print '%s.'%", ".join(map(str, squares))

or simply print ", ".join(map(str, squares))+'.'.

And if you're using python3, print becomes a builtin function . Unpack your list and use sep=',' as @Ashwini Chaudhary mentioned:

print(*squares, sep=', ')

str.join returns a string which is the concatenation of the strings in the iterable (squares in your example).

Upvotes: 2

Related Questions