简体   繁体   中英

How to remove the first and last portion of a string in Python?

How can i cut from such a string (json) everything before and including the first [ and everything behind and including the last ] with Python?

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

I want to have at least only

{
"cID" : "w2-502952",
"soldToId" : "34124",
}
...
...

String manipulation is not the way to do this. You should parse your JSON into Python and extract the relevant data using normal data structure access.

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

Addition to @Daniel Rosman answer, if you want all the list from JSON .

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

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

If you really want to do this via string manipulation (which I don't recommend), you can do it this way:

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

While I agree that Daniel's answer is the absolute best way to go, if you must use string splitting, you can try .find()

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

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

output will be everything between the [ and ] braces.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM