Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joining integer list [duplicate]

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?

like image 725
TheAnonyMoose1234512 Avatar asked Jan 29 '23 14:01

TheAnonyMoose1234512


1 Answers

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'
like image 56
heemayl Avatar answered Jan 31 '23 05:01

heemayl