suchadaprime
suchadaprime

Reputation: 13

Can't Convert List of String into Binary

I'm trying to convert a list for example mylist = ['apple', 'pineapple'] by using

[''.join(format(i, 'b') for i in bytearray(mylist, encoding ='utf-8'))]

but receive "encoding or errors without a string argument". the expected result is to be

['11000011110000111000011011001100101', '111000011010011101110110010111000011110000111000011011001100101']

How do I get the result in binary inside a list?

Upvotes: 0

Views: 49

Answers (1)

user2390182
user2390182

Reputation: 73460

I think you are applying some of the functions to the wrong objects. You are looking for something like:

mylist = ['apple', 'pineapple']

[''.join(format(b, 'b') for b in bytearray(i, 'utf-8')) for i in mylist]
# ['11000011110000111000011011001100101', 
#  '111000011010011101110110010111000011110000111000011011001100101']

or a little shorter:

[''.join(map('{:b}'.format, bytearray(i, 'utf-8'))) for i in mylist]

You must apply bytearray to each string in your list, not to the list itself. Next, you must format each byte and join the resulting strings.

Upvotes: 1

Related Questions