python-3.x - 在 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'
我可以看到它正在转换为字节,但在尝试编码和发送时仍然会出错。有人可以看看我在这里做错了什么吗?
谢谢
解决方案
当您期望一个list
对象时,您正在发送一个对象,这发生在您将元素转换为而不是容器时。您可以做的是将其序列化为字符串,然后将其转换为,例如:send
bytes
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'))
推荐阅读
- r - 在年度数据中插入与每个月对应的行
- excel - 如何获取存储文件的最后一个文件夹的名称(不使用宏)
- c# - Xamarin AppCenter Crashes.TrackError 未在 AppCenter 中显示我期望的详细信息
- mysql - 如何在 vb 中使用 mysql 执行与 mdf 数据库的连接
- python - 如何在锁定屏幕的IE中自动下载文件
- axapta - x++中可以通过多个连接检索的更新记录
- metronic - 如何将 metronic 主题集成到本地 formio 应用程序中
- sql-server - SQL 添加条件查询
- matlab - 如何从低通滤波器功能(firrrcos 或 rcosdesign)创建高通滤波器?MATLAB
- java - 通过 logger.log 覆盖处理程序级别