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
  • 561,645
  • 34
  • 376
  • 476
Vermillion
  • 1,056
  • 1
  • 12
  • 26

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,294
  • 1
  • 18
  • 33
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
  • 302,178
  • 90
  • 548
  • 690