6

I have an integer list that is supposed to represent binary:

x = [1, 0, 1, 1, 0, 0, 0, 0]
y = ''.join(x[:4])

I can't seem to join it, I get 'sequence item 0: expected str instance, int found'

However if I do

x = [str(1), str(0), str(1), str(1), str(0), str(0), str(0), str(0)]
y = ''.join(x[:4])

I get 'type error int object is not subscriptable' however I am not trying to to access ints.

Anyone know whats going on?

  • there is no way the second one gives that error. you must have done something else. run it yourself again. – Jason Hu Feb 24 '18 at 22:02
  • 1
    The str.join() method joins a sequence of strings, not ints. – jarmod Feb 24 '18 at 22:03
  • You can also map `str` to the list, `x = list(map(str, [1, 0, 1, 1, 0, 0, 0, 0]))` or `x = [str(x) for x in [1, 0, 1, 1, 0, 0, 0, 0]]`. – pylang Feb 24 '18 at 22:20

2 Answers2

8

str.join takes an iterable whose elements need to be strings, not integers.

I see that you have figured this out yourself, and your second method does work (the error you've given is presumably from some other code). But converting each int to str by hand like that is absolutely un-Pythonic. Instead, you can use a list comprehension/generator expression or map to do the conversion of ints to strs:

''.join(str(i) for i in x[:4])
''.join(map(str, x[:4]))

Example:

In [84]: ''.join(str(i) for i in x[:4])
Out[84]: '1011'

In [85]: ''.join(map(str, x[:4]))
Out[85]: '1011'
heemayl
  • 39,294
  • 7
  • 70
  • 76
0

One can also use functools reduce

from functools import reduce

reduce(lambda x, y: str(x) + str(y),[1, 0, 1, 1, 0, 0, 0, 0])
'10110000'
xskxzr
  • 12,442
  • 12
  • 37
  • 77
LetzerWille
  • 5,355
  • 4
  • 23
  • 26
  • quadratic algorithm here... Note, avoiding that is precisely the reason that `sum(['a','b','c'], '')` raises an error: `TypeError: sum() can't sum strings [use ''.join(seq) instead]` – juanpa.arrivillaga Feb 24 '18 at 23:01
  • you can do: `reduce(lambda x, y: x + str(y), [1, 0, 1, 1, 0, 0, 0, 0], '')` – Pierre D Mar 14 '19 at 23:56