TypeError: can only join an iterable
I'm trying to convert a list of integers to string. And it shows me the above error. What am I doing wrong?
Expected output: 10,5,78
l=[10,5,78]
s=''
for i in l:
s=s.join(i)
print(s)
Join doesn’t work the way you think it works.
What join does:
",".join(["a", "b", "c"])
Gives "a,b,c"
. Essentially it creates a string by elements from a list with what you provided before .join
, in this case it’s a comma.
So what you want can be achieved by
",".join(str(x) for x in l)
The inside expression changes the integers in list l
into strings before joining them by comma.
.join()
method acts on an existing string and accepts a list of strings. Join every item of the given list separated by the string acting on.
>>> l = [10, 5, 78]
>>> l = [str(i) for i in l] # map to a list of strings
>>> s = ','.join(l) # join all the strings separated by a comma
>>> s
'10,5,78'
s.join
"can only join an iterable". Is thei
an iterable? No, it's an integer, and integers cannot be iterated over. You can just dos = str(l)[1:-1]
, for examplel = [10,5,78]; ",".join([str(i) for i in l])
l
to the string"[10, 5, 78]"
and returns its characters except the first (1
) and the last (-1
) ones (the brackets). The[1:-1]
syntax is called slicings = ''.join(str(_) for _ in l)
ors = ','.join(str(_) for _ in l)
, if you want the numbers comma separated.str(l)[1:-1].replace(' ', '')