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)
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Vishal Pallikonda
  • 161
  • 1
  • 1
  • 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 Jan 04 '20 at 14:18
  • 2
    `l = [10,5,78]; ",".join([str(i) for i in l])` – moo Jan 04 '20 at 14:23
  • @ForceBru That worked like magic. Can you please explain what [1:-1] does? – Vishal Pallikonda Jan 04 '20 at 14:24
  • 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 Jan 04 '20 at 14:26
  • @ForceBru this solution gives extra space after comma and so doesn’t fit the expected output and it also doesn’t help VishalPallikonda learn the join syntax. – Tim Jan 04 '20 at 14:29
  • 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 Jan 04 '20 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 Jan 04 '20 at 14:34
  • @ForceBru It’s an interesting and imaginative solution. There is no doubt :) But I think for beginners it’s better to master the basics before trying something fancy like this ;) – Tim Jan 04 '20 at 14:43

2 Answers2

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.

Tim
  • 3,178
  • 1
  • 13
  • 26
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'
Pedro Rodrigues
  • 2,520
  • 2
  • 27
  • 26