str.split
is a method that is only available on the str
type. How it works is explained in the docs:
str.split([sep[, maxsplit]])
Return a list of the words in the string, using sep
as the delimiter string. If
maxsplit
is given, at most maxsplit
splits are
done (thus, the list will have at most maxsplit+1
elements). If
maxsplit
is not specified or -1
, then there is no limit on the number
of splits (all possible splits are made).
What you want to use here is str.join
:
>>> l = [1, 2, 3, 4]
>>> map(str, l) # Just to demonstrate
['1', '2', '3', '4']
>>> '\t'.join(map(str, l))
'1\t2\t3\t4'
>>>
According to the 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.
In the above example, str.join
takes the list of strings returned by map(str, l)
:
['1', '2', '3', '4']
and concatenates all of its items together, separating each one by \t
. The result is the string:
'1\t2\t3\t4'
Also, in case you are wondering, map
is being used in the above example to convert the list of integers into a list of strings. An alternate approach would be to use a list comprehension:
>>> l = [1, 2, 3, 4]
>>> '\t'.join([str(x) for x in l])
'1\t2\t3\t4'
>>>
Both solutions are about equivalent, but you need to use one of them because str.join
requires an iterable of strings.