I have a string like this
string = 'LVPV(filler)PITN(notneeded)ATLDQITGK[0;0;0;0;0;6;2;0;0;5;0]'
How do I remove everything in the brackets and parentheses? Like so:
string = 'LVPVPITNATLDQITGK'
Regular expression is ideal for these tasks and fortunately python standard library provides support for regex
>>> re.sub(r"[\(\[].*?[\)\]]", "", st)
'LVPVPITNATLDQITGK'
The above pattern substitutes with empty string any thing that is within a parenthesis or bracket block.
Note Regex patterns are difficult to make robust and can easily digress and break for exceptional patterns like
'LVPV(filler]PITN[notneeded)ATLDQITGK[0;0;0;0;0;6;2;0;0;5;0]'
So you need to be certain about your input data and its expected output
And nevertheless, you can always do this without regex
>>> import string
>>> ''.join(st.translate(string.maketrans("()[]"," "*4)).split(' ')[::2])
'LVPVPITNATLDQITGK'
I suggest you to use alternation operator.
>>> string = 'LVPV(filler)PITN(notneeded)ATLDQITGK[0;0;0;0;0;6;2;0;0;5;0]'
>>> re.sub(r"\([^()]*\)|\[[^\[\]]*\]", "", string)
'LVPVPITNATLDQITGK'
>>> st = 'LVPV(filler]PITN[notneeded)ATLDQITGK[0;0;0;0;0;6;2;0;0;5;0]'
>>> re.sub(r"\([^()]*\)|\[[^\[\]]*\]", "", st)
'LVPVATLDQITGK'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.