简体   繁体   中英

How to remove the brackets from list in Python?

I have a list:

list1 = ['[0', '"properties"', '"ipv4"', '0', '"value"]']

I want the output:

list1= 0 , "properties" , "ipv4" , 0 , "value"

I have tried:

ini_string = ini_string.replace('[', '').replace(']','')

But it is giving an output like:

> 0 
> query_json2 = query_json2[ini_string] TypeError: list indices must be integers or slices, not str

Try this...

list1 = ['[0', '"properties"', '"ipv4"', '0', '"value"]']
a = [a.replace('[', '').replace(']', '') for a in list1]
b = ', '.join(a)
print(b)

Let's assume if you are iterate via dictionary. So after the above code.

some_dict = {
    0: {
        'properties': {
            'ipv4': {
                0: {
                    'value': 'new_value'
                }
            }
        }
    }
}

for x in a:
    if x.isdigit():
        new = some_dict[int(x)]
    else:
        x = x.replace('"', '')
        new = some_dict[x]
    some_dict = new


print(some_dict)
import re
result = ''
for word in list1:
  cleanWord = ''.join(re.split('[|]'))
  result += cleanWord + ' ,'
print("list 1 = " + result[:-2])

Essentially you strip it of [ and ] and append it to a string to output

Try this out....

list1 = ['[0', '"properties"', '"ipv4"', '0', '"value"]']
for i in range(0,len(list1)):
    if "[" in list1[i] or "]" in list1[i]:
        list1[i] = re.sub(r'[^\w]', '', list1[i])
print(",".join(list1))```

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