简体   繁体   中英

Python removing ([ from a text file

So basically in my text file, the information is layed out like this

([x,x,x,x,x,x,x,x,x,x,,x],[x,x,x,x],[x,x,x])

how would i remove the brackets so that all of it becomes one array and i can just call it by position[0] or position[10] ?

will it help ? Try out :

list2=r"([x,x,x,x,x,x,x,x,x,x,,x],[x,x,x,x],[x,x,x])"

old_list=[i for i in list2]

new_list=[i for i in old_list if i!=',' and i!='(' and i!=')' and i!='[' and i!=']']

print(new_list)

output:

['x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x']

Update soltion basis on your screenshot :

list_22=([1,2,3,4],["couple A","couple B","couple C"],["f","g","h"])

print([j for i in list_22 for j in i])

output:

[1, 2, 3, 4, 'couple A', 'couple B', 'couple C', 'f', 'g', 'h']

You can flatten the lists inside the tuple by looping over them like this.

tuple_of_lists = ([x,x,x,x,x,x,x,x,x,x,,x],[x,x,x,x],[x,x,x])
resulting_list = []
for lis in tuple_of_lists:
    resulting_list.extend(lis)

I hope it helps.

Edited:- May be this function can help.

def formatter(string):
    l = len(string)
    to_avoid = {',', '[', ']', '(', ')', '"'}
    lis = []
    temp = ''
    for i in range(l):
        if string[i] in to_avoid:
            if temp != '':
                lis.append(temp)
            temp = ''
            continue
        else:
            temp += string[i]
    return lis

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM