Python 如何从字符串中选择特定字符串?

Python 如何从字符串中选择特定字符串?,python,string,list,Python,String,List,我有一个如下列表: ["X['name']", "X['fields']['height']", "X['fields']['date']", "X['fields']['id']['doc']['result']['zipcode']"] 如何获得一个新列表,只需: ['name','height','date','zipcode'] 所以基本上只是每个项目最后一个括号中的字符串 提前谢谢 此代码使用re

我有一个如下列表:

["X['name']",
 "X['fields']['height']",
 "X['fields']['date']",
 "X['fields']['id']['doc']['result']['zipcode']"]
如何获得一个新列表,只需:

['name','height','date','zipcode']
所以基本上只是每个项目最后一个括号中的字符串


提前谢谢

此代码使用re模块和regex在单引号字符上拆分。然后,默认情况下,所需的单词将是由
re.split()
生成的列表中倒数第二个字符串


此代码使用re模块和regex在单引号字符上拆分。然后,默认情况下,所需的单词将是由
re.split()
生成的列表中倒数第二个字符串


您可以使用内置的Python方法来帮助您实现这一点。您需要了解的主要内容是如何处理列表中的列表/项目以及字符串操作。这里有一个我发现有助于学习的链接

我还在下面的注释中加入了一些代码,这样可以帮助您理解每个块的作用。还有一行代码可以帮助处理在列表项中找不到括号的情况

finalList = []
string = ["X['name']",
         "X['fields']['height']",
         "X['fields']['date']",
         "X['fields']['id']['doc']['result']['zipcode']"]

for item in string:
    # finds no. of brackets in string
    occurrences = item.count("['")
    # splits off the nth occurence of string and stores two bits of string in a list
    parts = item.split("['", occurrences)
    # for situation where there are no brackets
    start = item.find("['")

    # no brackets found returns -1
    if start == -1:
        print('String not Found')
    # extracts specific piece of string from the list, cleans then stores in final output list
    else:
        extractedString = parts[len(parts)-1]
        cleanedExtractedString = extractedString.replace("']", "")
        finalList.append(cleanedExtractedString) 

print(finalList);

您可以使用内置的Python方法来帮助您实现这一点。您需要了解的主要内容是如何处理列表中的列表/项目以及字符串操作。这里有一个我发现有助于学习的链接

我还在下面的注释中加入了一些代码,这样可以帮助您理解每个块的作用。还有一行代码可以帮助处理在列表项中找不到括号的情况

finalList = []
string = ["X['name']",
         "X['fields']['height']",
         "X['fields']['date']",
         "X['fields']['id']['doc']['result']['zipcode']"]

for item in string:
    # finds no. of brackets in string
    occurrences = item.count("['")
    # splits off the nth occurence of string and stores two bits of string in a list
    parts = item.split("['", occurrences)
    # for situation where there are no brackets
    start = item.find("['")

    # no brackets found returns -1
    if start == -1:
        print('String not Found')
    # extracts specific piece of string from the list, cleans then stores in final output list
    else:
        extractedString = parts[len(parts)-1]
        cleanedExtractedString = extractedString.replace("']", "")
        finalList.append(cleanedExtractedString) 

print(finalList);