简体   繁体   English

如何使用 python 从字符串中删除括号'[]'?

[英]How to remove brackets '[ ]'from string using python?

I am unable to remove brackets '[ ]' from the below string.我无法从以下字符串中删除括号'[ ]'

I am getting this response through an API:我通过 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\\'\"'"
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)

You can use the str.join for this您可以为此使用str.join

print(', '.join(content_line))

# 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"'

I solved this by using String instead of tuples.我通过使用字符串而不是元组解决了这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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