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)
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'