'How to remove '[' character from a string with re.sub function? [duplicate]
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 1:[1]
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)
Solution 2:[2]
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']
Solution 3:[3]
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']
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Thomas |
| Solution 2 | Tim Biegeleisen |
| Solution 3 | Albert Winestein |
