Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading