1

I have a string

statement = 'P ∧ (Q ∨ R) ↔ (P ∧ Q) ∨ (P ∧ R)'

I want to store each string that is within parentheses, like this:

['Q ∨ R', 'P ∧ Q', 'P ∧ R']

How can this be done?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Vermillion
  • 1,238
  • 1
  • 14
  • 29

2 Answers2

6
>>> import re
>>> [s[1:-1] for s in re.findall(r'\(.*?\)', 'P ∧ (Q ∨ R) ↔ (P ∧ Q) ∨ (P ∧ R)')]
['Q ∨ R', 'P ∨ Q', 'P ∧ R']
Denny Weinberg
  • 2,492
  • 1
  • 21
  • 34
4

It's a good use-case for regex:

>>> import re
>>> re.findall(r'\((.*?)\)', statement)
['Q ∨ R', 'P ∧ Q', 'P ∧ R']

The ? character in the pattern is a non-greedy modifier suffix.

wim
  • 338,267
  • 99
  • 616
  • 750