繁体   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