LLL
LLL

Reputation: 469

How to select specific string from strings?

I have a list that looks like this:

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

How do I get a new list with just:

['name','height','date','zipcode']

So basically just the string in the last bracket from every item.

Thanks in advance!

Upvotes: 0

Views: 1093

Answers (2)

tr2002a
tr2002a

Reputation: 116

This code uses the re module and regex to split on the single quote character. Then, by default, the desired word will be the second to last string in the list generated by re.split().

import re
lists = ["X['name']",
 "X['fields']['height']",
 "X['fields']['date']",
 "X['fields']['id']['doc']['result']['zipcode']"]
lastwords = []
for s in lists:
    lw = re.split("[X']", s)
    lastw = lw[len(lw)-2]
    lastwords.append(lastw)

Upvotes: 2

MTay
MTay

Reputation: 129

You can use the built-in Python methods to help you with this. Main things you'll need to understand are how to handle lists / items in lists and string manipulation. Here's a link that I found helpful with learning about list and string manipulation.

I've also included some code below with comments so it can help you understand what each chunk does. There's also an additional line of code that helps handle situations where brackets cannot be found in the list item.

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);

Upvotes: 0

Related Questions