pikachu
pikachu

Reputation: 612

Input to the python join method can't be a list of numbers?

This gives me an error:

   a = [1,2,3]
   '\t'.join(a)

Is this because of the list elements being integers?

Upvotes: 0

Views: 347

Answers (2)

Nadir Sampaoli
Nadir Sampaoli

Reputation: 5555

Indeed. Python needs explicit type conversion since it's strongly-typed.

>>> a = [1,2,3]
>>> '\t'.join(map(str, a))
'1\t2\t3'

Function map applies function (passed as first argument) to iterable (passed as second argument).

In this case it converts (str) each element of a into a string and returns the resulting list, that is consequently passed to method join of object '\t'.

Upvotes: 1

Green Su
Green Su

Reputation: 2348

see http://docs.python.org/library/stdtypes.html#str.join

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

So the target should be array of strings.

Upvotes: 0

Related Questions