欣赏单行习语中的帮助,以有效地执行以下操作。

我有一个由大括号分隔的组的字符串,如下所示:

{1:xxxx}{2:xxxx}{3:{10:xxxx}}{4:xxxx\r\n:xxxx}....

如何将其转换为字典格式?
dict={1:'xxx',2:'xxxx',3:'{10:xxxx}'},4:'xxxx\r\n:xxxx'}

最佳答案

这就是我将如何做到的:

raw = """{1:xxxx}{2:xxxx}{3:{10:xxxx}}{4:'xxxx\r\n:xxxx'}"""

def parse(raw):
    # split into chunks by '}{' and remove the outer '{}'
    parts = raw[1:-1].split('}{')
    for part in parts:
        # split by the first ':'
        num, data = part.split(':', 1)
        # yield each entry found
        yield int(num), data

# make a dict from it
print dict(parse(raw))

就像在您的示例中一样,它将 '{10:xxxx}' 保留为字符串。

关于python - 在python中拆分大括号分组字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16356382/

10-13 07:15