簡體   English   中英

如何獲取 python 中字符串中括號之間的數據?

[英]How to get Data between the brackets in string in python?

我有一個這樣的字符串list = ['Fruits in ['Apples', 'Mangoes']','Vegetables in ['Carrots', 'Onion']']我想要一個包含正方形內的值的列表像這樣的列表值括號'list1 = [[Apples', 'Mangoes'], ['Carrots', 'Onion']請幫幫我。

你可以這樣做:

    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}')
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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM