Home > other >  How to get Data between the brackets in string in python?
How to get Data between the brackets in string in python?

Time:01-16

I have a list of strings like this list = ['Fruits in ['Apples', 'Mangoes']','Vegetables in ['Carrots', 'Onion']'] I want a list which has the values inside the square brackets of list values like this 'list1 = [[Apples', 'Mangoes'], ['Carrots', 'Onion'] please help me with this.

CodePudding user response:

You can do something like this:

    new_list = []
    list = ['Fruits in ["Apples", "Mangoes"]','Vegetables in ["Carrots", "Onion"]']
    for elem in list:
        # gets the text after the opening bracket and avoids the last character
        brackets = elem.split("[")[1][:-1]
        inside_list = brackets.split(',')

        new_list.append(inside_list)
    print(f'{new_list}')

CodePudding user response:

import re

def extract_items(s):
    return re.compile("(?<=[^\(]')\w ").findall(s)

mylist = ["Fruits in ['Apples', 'Mangoes']","Vegetables in ['Carrots', 'Onion']"]
list1 = list(map(extract_items,  mylist))
print(list1)
  •  Tags:  
  • Related