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?
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 int
s to str
s:
''.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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With