Python 修复格式错误的字符串?
我有来自TCP行的数据作为字典列表。但有时我一次收到两包。他们看起来像Python 修复格式错误的字符串?,python,string,Python,String,我有来自TCP行的数据作为字典列表。但有时我一次收到两包。他们看起来像 [{"property1":"value1", "property2":"value2"}, {"property1":"value1", "property2":"value2"}][{"property1":"value1", "property2":"value2"}][{"property1":"value1", "property2":"value2"}, {"property1":"value1", "prope
[{"property1":"value1", "property2":"value2"}, {"property1":"value1", "property2":"value2"}][{"property1":"value1", "property2":"value2"}][{"property1":"value1", "property2":"value2"}, {"property1":"value1", "property2":"value2"}]
我想把它转换成:
[{"property1":"value1", "property2":"value2"}, {"property1":"value1", "property2":"value2"}, {"property1":"value1", "property2":"value2"},
{"property1":"value1", "property2":"value2"}, {"property1":"value1", "property2":"value2"}]
您可以通过两个步骤完成此操作:
][
替换为,
,因为这些连续的方括号表示单独的数据包,连接它们的最简单方法是用逗号替换ast.literal\u eval
的字典,即“safe”eval
这里的假设是您正在以字符串的形式接收这些“数据包”。您可以通过两个步骤完成此操作:
][
替换为,
,因为这些连续的方括号表示单独的数据包,连接它们的最简单方法是用逗号替换ast.literal\u eval
的字典,即“safe”eval
这里的假设是您正在以字符串形式接收这些“数据包”。输入
l='[{"property1":"value1", "property2":"value2"}, {"property1":"value1", "property2":"value2"}][{"property1":"value1", "property2":"value2"}][{"property1":"value1", "property2":"value2"}, {"property1":"value1", "property2":"value2"}]'
使用re
import re
re.findall("\[?([^\]]+)?\]", l)
输出
['{"property1":"value1", "property2":"value2"}, {"property1":"value1", "property2":"value2"}',
'{"property1":"value1", "property2":"value2"}',
'{"property1":"value1", "property2":"value2"}, {"property1":"value1", "property2":"value2"}'
]
输入
使用re
import re
re.findall("\[?([^\]]+)?\]", l)
输出
['{"property1":"value1", "property2":"value2"}, {"property1":"value1", "property2":"value2"}',
'{"property1":"value1", "property2":"value2"}',
'{"property1":"value1", "property2":"value2"}, {"property1":"value1", "property2":"value2"}'
]
ast.literal_eval(string.replace('][',','))
您得到的是字符串形式的吗?ast.literal_eval(string.replace('][',','))
你得到的是字符串的形式吗?两种形式中哪一种更快。@Piyusdivyanakar正则表达式通常比纯字符串替换慢得多。好的,谢谢:)我实现了字符串替换,两种形式中的哪一种更快。@Piyusdivyanakar正则表达式通常比纯字符串替换慢得多。好的,谢谢:)我建议修订了字符串替换