简体   繁体   English

无法将字符串列表转换为二进制

[英]Can't Convert List of String into Binary

I'm trying to convert a list for example mylist = ['apple', 'pineapple'] by using我正在尝试转换一个列表,例如 mylist = ['apple', 'pineapple'] 通过使用

[''.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?如何在列表中获得二进制结果?

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.您必须将bytearray应用于列表中的每个字符串,而不是列表本身。 Next, you must format each byte and join the resulting strings.接下来,您必须格式化每个字节并连接生成的字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM