How to replace all square brackets and their values with empty strings if you don't know how many square brackets are there?
data = "[a] 1 [b] test [c] other characters"
I want the data to be " 1 test other characters"
.
How to replace all square brackets and their values with empty strings if you don't know how many square brackets are there?
data = "[a] 1 [b] test [c] other characters"
I want the data to be " 1 test other characters"
.
You can split your string on the bracket parts using a regex:
import re
data = "[a] 1 [b] 2 [c]"
parts = re.split(r'\[.*?\]', data)
# ['', ' 1 ', ' 2 ', '']
out = '[' + ' '.join(parts) + ']'
print(out)
# [ 1 2 ]
Another verbose answer would be:
import re
data = "[a] 1 [b] test [c] other characters"
pattern = '\[.*?\]' #any character(s) with [ ]
unwanted = set(re.findall(pattern,data))
results = ' '.join(i for i in data.split()
if i not in unwanted)
print(results)
# 1 test other characters
Updated
Addition condition
Problem > "[a] 1 [b] test [1] other [c]haracters"
Due to .split()
this will not be replaced
import re
data = "[a] 1 [b] test [1] other [c]haracters"
pattern = '\[.*?\]' #any character(s) with [ ]
print(re.sub(pattern,'',data))
# " 1 test other haracters"
To remove the extra spaces
_ = re.sub(pattern,'',data).split()
print(' '.join(i for i in _ if i))
# "1 test other haracters"
Try regex substitute.
import re
data = "[a] 1 [b] 2 [c]"
new = re.sub("([[a-z]*])", "", data)