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']
CodePudding user response:
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)
CodePudding user response:
The regex pattern you seem to want here is ^\[|\]$
:
depth_split = ['[575,0]']
depth_split[0] = re.sub(r'^\[|\]$', '', depth_split[0])
print(depth_split) # ['575,0']
CodePudding user response:
If the brackets are always at the beginning and end of the strings in your list then you can do this with a string slice as follows:
depth_split = ['[575,0]']
depth_split = [e[1:-1] for e in depth_split]
print(depth_split)
Output:
['575,0']