简体   繁体   English

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

[英]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? 如何使用Python从这样的字符串(json)剪切掉所有内容,包括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. 您应该将JSON解析为Python,并使用常规数据结构访问权限提取相关数据。

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

Addition to @Daniel Rosman answer, if you want all the list from JSON . 如果您要从JSON所有list ,请添加@Daniel Rosman答案。

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

output will be everything between the [ and ] braces. 输出将是[]大括号之间的所有内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如果字符串中的第一个或最后一个字符是 $ 在 python 中删除它 - If first or last character from string is $ remove it in python 如何在 Python 中部分拆分并取字符串的第一部分? - How to partial split and take the first portion of string in Python? 如何删除字符串的第一个和最后一个字母? - How to remove the first and last letter of a string? Python:从字符串列表中删除一部分字符串 - Python: Remove a portion of a string from a list of strings Python - 如何查找和删除由多组括号组成的字符串的第一个和最后一个右括号 - Python - How to find and remove the first and last closing bracket of a string that consists of many sets of brackets in between 从 Python 字符串中删除第一行和最后一行的最快方法 - Fastest way to remove first and last lines from a Python string Python:有没有一种方法可以查找和删除字符串中字符的第一个和最后一个出现的位置? - Python: Is there a way to find and remove the first and last occurrence of a character in a string? 如何在Python中删除字符串中的最后一个单词? - How to remove a last word in the string in Python? 如何删除长度可变的字符串的一部分 - How to remove a portion of a string with variable length python-如何反复删除字符串中的第一次出现的python? - How to remove first occurrence in string repeatedly python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM