我目前正在使用 python 通过 433Mhz 链接将 python 字典从一个树莓派传输到另一个树莓派,使用虚拟线路 (vw.py) 发送数据。
vw.py 的问题是发送的数据是字符串格式。
我已成功接收到 PI_no2 上的数据,现在我正在尝试重新格式化数据,以便将其放回字典中。
我创建了一个小片段来测试,并创建了一个临时字符串,其格式与从 vw.py 接收到的格式相同
到目前为止,我已经成功地在冒号处拆分了字符串,现在我正试图摆脱双引号,但没有成功。
my_status = {}
#temp is in the format the data is recieved
temp = "'mycode':['1','2','firstname','Lastname']"
key,value = temp.split(':')
print key
print value
key = key.replace("'",'')
value = value.replace("'",'')
my_status.update({key:value})
print my_status
给出结果
'mycode'
['1','2','firstname','Lastname']
{'mycode': '[1,2,firstname,Lastname]'}
我要求值的格式
['1','2','firstname','Lastname']
但是 strip 去掉了所有单个语音标记。
请您参考如下方法:
你可以使用ast.literal_eval
import ast
temp = "'mycode':['1','2','firstname','Lastname']"
key,value = map(ast.literal_eval, temp.split(':'))
status = {key: value}
会输出
{'mycode': ['1', '2', 'firstname', 'Lastname']}
