Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 修复格式错误的字符串?_Python_String - Fatal编程技术网

Python 修复格式错误的字符串?

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

我有来自TCP行的数据作为字典列表。但有时我一次收到两包。他们看起来像

[{"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正则表达式通常比纯字符串替换慢得多。好的,谢谢:)我建议修订了字符串替换