簡體   English   中英

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

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

如何使用Python從這樣的字符串(json)剪切掉所有內容,包括Python之前的所有內容,以及第一個 [以及后面的所有內容,包括最后一個 ]

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

我至少要

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

字符串操作不是這樣做的方法。 您應該將JSON解析為Python,並使用常規數據結構訪問權限提取相關數據。

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

如果您要從JSON所有list ,請添加@Daniel Rosman答案。

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

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

如果您真的想通過字符串操作(我不建議這樣做),可以這樣:

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

雖然我同意丹尼爾(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)

輸出將是[]大括號之間的所有內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM