0

I am unable to remove brackets '[ ]' from the below string.

I am getting this response through an API:

[["b", "m", "l", "a", "p", "c"], [["20,5,93767,TEST,Watch,16"], ["19,5,767, TEST,Lamb,23"], ["19,5,3767,TEST,DB,99"]]]

I have to change this response to:

"b", "m", "l", "a", "p", "c", "20,5,93767,TEST,Watch,16", "19,5,767, TEST,Lamb,23", "19,5,3767,TEST,DB,99"

I have to use python

I am using this code to remove it:

(str(content_line)[1:-1])

now I am getting this output:

"\"b', 'm', 'l', 'a', 'p', 'c\",'\"\\'20,5,93767,TEST,Watch,16\\'\", \"\\'19,5,767, TEST,Lamb,23, \"\\'19,5,3767,TEST,DB,99\\'\"'"
Alan Kavanagh
  • 9,425
  • 7
  • 41
  • 65
Kapil Shukla
  • 179
  • 1
  • 10
  • This looks more like a list of lists of strings. If it truely is a string, you could just try `str.replace("[", "")` and `str.replace("]", "")` – tst Dec 12 '19 at 12:21
  • Does this answer your question? [How to make a flat list out of list of lists?](https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-list-of-lists) – JohnRW Dec 12 '19 at 12:25

4 Answers4

3
def flatten(content_line):
    result = []
    for element in content_line:
        if isinstance(element, list):
            result.extend(flatten(element))
        else:
            result.append(element)
    return result

flatten(content_line)
Dishin H Goyani
  • 7,195
  • 3
  • 26
  • 37
  • Could you add some simple explanation about what exactly this code snippet is doing? – deHaar Dec 12 '19 at 12:32
  • it's a recursive function that flatten a python list. If a list contains another list, it will recursively flatten that list and return a simple list back. – Chengcheng Ji Dec 12 '19 at 16:27
  • Yes. This is the most useful to me as I am also getting a list. Still my output is not what I wanted. Its lookin like this now: ["b", "m", "l", "a", "p", "c", "20,5,93767,TEST,Watch,16", "19,5,767, TEST,Lamb,23", "19,5,3767,TEST,DB,99"] – Kapil Shukla Dec 13 '19 at 09:11
  • if you want a string output instead, you can use `', '.join(flatten(content_line))` – Chengcheng Ji Dec 14 '19 at 13:17
1

You can use the str.join for this

print(', '.join(content_line))

Reznik
  • 2,663
  • 1
  • 11
  • 31
1
# input string
a_st = """ [["b", "m", "l", "a", "p", "c"], [["20,5,93767,TEST,Watch,16"], ["19,5,767, TEST,Lamb,23"], ["19,5,3767,TEST,DB,99"]]] """

# replace brackets '[]' with ''
output = a_st.replace('[','').replace(']','')

# output
print(output)
>>> '"b", "m", "l", "a", "p", "c", "20,5,93767,TEST,Watch,16", "19,5,767, TEST,Lamb,
23", "19,5,3767,TEST,DB,99"'
Dishin H Goyani
  • 7,195
  • 3
  • 26
  • 37
0

I solved this by using String instead of tuples.

Kapil Shukla
  • 179
  • 1
  • 10