如何在Python中删除字符串的第一部分和最后一部分?

时间:2018-09-24 14:24:14

标签: python

如何从这样的字符串(json)切掉 first [之前和包括的所有内容以及 last {{1} }与Python?

]

我至少要拥有一个

{
    "Customers": [
        {
           "cID": "w2-502952",
           "soldToId": "34124"
        },
        ...
        ...
    ],
        "status": {
        "success": true,
        "message": "Customers: 560",
        "ErrorCode": ""
    }
}

4 个答案:

答案 0 :(得分:4)

字符串操作不是。您应该将JSON解析为Python,并使用常规数据结构访问权限提取相关数据。

obj = json.loads(data)
relevant_data = obj["Customers"]

答案 1 :(得分:1)

如果您想要list中的所有JSON,请添加@Daniel Rosman答案。

result = []
obj = json.loads(data)

for value in obj.values():
    if isinstance(value, list):
        result.append(*value)

答案 2 :(得分:0)

如果您真的想通过字符串操作来做到这一点(我不建议这样做),则可以这样操作:

start = s.find('[') + 1
finish = s.find(']')
inner = s[start : finish]

答案 3 :(得分:0)

虽然我同意丹尼尔(Daniel)的回答是绝对最佳的方法,但如果必须使用字符串拆分,则可以尝试.find()

string = #however you are loading this json text into a string

start = string.find('[')
end = string.find(']')
customers = string[start:end]
print(customers)

输出将是[]大括号之间的所有内容。

相关问题