pythonarraysstringpython-resquare-bracket

How to remove '[' character from a string with re.sub function?


I want to remove the '[' square bracket character from a string. I am using re library. I had no problems with this square bracket ']' but I still having problem with this square bracket '['.

My code:

depth_split = ['[575,0]']

new_string = re.sub(']','',depth_split) #working
newnew_string = re.sub('[','',new_string) #not working

PS: I'm using python.

The output that I have : ['[575,0']

The output that I expeting : ['575,0']


Solution

  • There is no need of using regex here since it can be done easily using str.replace():

    new_string= '[575,0]'
    new_string = new_string.replace(']', '')
    new_string = new_string.replace('[', '')
    print(new_string)
    

    But if using regex is necessary try:

    import re
    
    depth_split = '[575,0]'
    
    new_string = re.sub(r'\]|\[','',depth_split) #working
    print(new_string)