将字符串列表转换为 Python3 中的字节

Converting list of string to bytes in 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'

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

谢谢

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

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'))