Reputation: 139
I have a string something like this:
OPEN BRANCH FROM BUS 264604 [19BVEO 345.00] TO BUS
264888 [19LRTY 345.00] CKT 1
I would like to remove the substring enclosed between "[" and "]". The result should be something like this:
OPEN BRANCH FROM BUS 264604 TO BUS 264888 CKT 1
Thanks,
Upvotes: 0
Views: 625
Reputation: 4744
Regex is one option:
import re
str_in = 'PEN BRANCH FROM BUS 264604 [19BVEO 345.00] TO BUS 264888 [19LRTY 345.00] CKT 1'
str_out = re.sub('\\[[^\\]]*\\]', '', str_in)
Prints str_out
as
PEN BRANCH FROM BUS 264604 TO BUS 264888 CKT 1
The regex pattern is from this post for R. It will match and replace with an empty string any character sequence enclosed by square brackets in the entire string str_in
.
It's possible that you also want to remove the extra space created from the removal of bracketed text. If you noticed, there are two spaces left from the removal instead of just one. If that's the case, you can add the following line after re.sub
,
str_out = (' ').join(str_out.split(' '))
so str_out
becomes,
PEN BRANCH FROM BUS 264604 TO BUS 264888 CKT 1
Upvotes: 1
Reputation: 1383
You can use split
:
s='OPEN BRANCH FROM BUS 264604 [19BVEO 345.00] TO BUS 264888 [19LRTY 345.00] CKT 1'
pieces=[s.split(']')[-1] for s in s.split('[')]
print(pieces)
['OPEN BRANCH FROM BUS 264604 ', ' TO BUS 264888 ', ' CKT 1']
sentence=''.join(pieces)
print(sentence)
'OPEN BRANCH FROM BUS 264604 TO BUS 264888 CKT 1'
Upvotes: 1