首页 > 解决方案 > 在 Python3 中将字符串列表转换为字节

问题描述

我一直在尝试将字符串元素列表转换为字节,以便可以将其发送到服务器。以下是我的代码片段:-

    ls_queue=list(q.queue)
    print("Queue converted to list elements:::",ls_queue)

    encoded_list=[x.encode('utf-8') for x in ls_queue]
    print("Encoded list:::",encoded_list)
    s.send(encoded_list)

我得到的输出是:

 Encoded list::: [b'madhav']
 Exception in Tkinter callback
 Traceback (most recent call last):
 File "C:\Users\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1883, in 
 __call__
 return self.func(*args)
 File "Practice_Client_Server.py", line 149, in Word_Append_Window
  s.send(encoded_list)
 TypeError: a bytes-like object is required, not 'list'

我可以看到它正在转换为字节,但在尝试编码和发送时仍然会出错。有人可以看看我在这里做错了什么吗?

谢谢

标签: python-3.xmultithreadinglistqueuebyte

解决方案


当您期望一个list对象时,您正在发送一个对象,这发生在您将元素转换为而不是容器时。您可以做的是将其序列化为字符串,然后将其转换为,例如:sendbyteslistbyteslistJSONbytes

import json

l = ['foo', 'bar']
l_str = json.dumps(l)
l_bytes = l_str.encode('utf-8')
send(l_bytes)

然后你可以在你的服务器上阅读它,做相反的事情:

reconstructed_l = json.loads(l_bytes.decode('utf-8'))

推荐阅读