2
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)
8
  • 3
    As the error message says, s.join "can only join an iterable". Is the i an iterable? No, it's an integer, and integers cannot be iterated over. You can just do s = str(l)[1:-1], for example
    – ForceBru
    Commented Jan 4, 2020 at 14:18
  • 2
    l = [10,5,78]; ",".join([str(i) for i in l])
    – moo
    Commented Jan 4, 2020 at 14:23
  • 2
    @VishalPallikonda, it converts 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 slicing
    – ForceBru
    Commented Jan 4, 2020 at 14:26
  • 1
    You just need s = ''.join(str(_) for _ in l) or s = ','.join(str(_) for _ in l), if you want the numbers comma separated.
    – accdias
    Commented Jan 4, 2020 at 14:30
  • 1
    @Tim, the output is very close, though (I'm 90% sure the spaces don't matter that much here), and it's simple to make it match the desired output exactly: str(l)[1:-1].replace(' ', '')
    – ForceBru
    Commented Jan 4, 2020 at 14:34

2 Answers 2

5

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.

0
2

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.