Delete 2 parentheses (Python)

Asked 2 years ago, Updated 2 years ago, 19 views

Hello, I have a question because there is a blockage in coding.

The input is as follows

You are my happiness, but I love you

The (happiness) part is left with one parenthesis, and (happiness (you)) is made up of two parentheses, so it should be deleted.

Output is as follows

You are my happiness but I love you

If you use a regular expression, you can only make up the part where you delete the parentheses.


import re

bra = r'\([^)]*\)'
s = "You're my happiness, but you're not my happiness. I love you."
text = re.sub(bra,'',s)
print(text)

I don't get the results right. I need your help!

python

2022-09-20 10:52

1 Answers

I tried to solve it with the regular expression, but it's still too much for me. This is possible with the regular expression +@.

import re

b = r'\(.*?\)'
s = "You're my happiness, but you're not my happiness. I love you."
a = re.findall(b, s)
for i in a:
    print(i)
    if i.count('(') == 2:
        s = s.replace(i + ')', '')
print(s)
>> (happiness)
(You're not happy)
You are my happiness, but I love you


2022-09-20 10:52

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.