且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从字符串中提取Python字典

更新时间:2022-06-22 22:45:15

来自@AChampion的建议。

From @AChampion's suggestion.

>>> import re
>>> import ast
>>> x = ast.literal_eval(re.search('({.+})', data).group(0))
>>> x
{'Bar': 'value', 'Foo': '1002803'}

因此您要寻找的模式是 re.search('({。+})',data)

so the pattern you're looking for is re.search('({.+})', data)

您应该使用字符串提取花括号,因此 ast.literal_eval 可以将字符串转换为python字典。您也不需要 r 前缀作为 {} 在捕获组中,()会按字面值进行匹配。

You were supposed to extract the curly braces with the string, so ast.literal_eval can convert the string to a python dictionary . you also don't need the r prefix as { or } in a capturing group, () would be matched literally.