0

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!

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.