Michael
Michael

Reputation: 13914

Python Finding All Open Parentheses in a String

I am trying to find the position of all open parentheses in a string. Following this answer, I am able to find the positions of letters, but I cannot find the position of parentheses. For example, l = [3, 4], but when I try and find all ( I get error: unbalanced parenthesis.

import re

s = "(Hello("
l = [m.start() for m in re.finditer('l', s)]
openp = [m.start() for m in re.finditer('(', s)]

Upvotes: 0

Views: 1725

Answers (1)

Andrew Clark
Andrew Clark

Reputation: 208455

In regular expressions ( is a special character that denotes the beginning of a group. To match a literal ( you will need to either escape it with a backslash or put it into a character class:

openp = [m.start() for m in re.finditer(r'\(', s)]

... or:

openp = [m.start() for m in re.finditer(r'[(]', s)]

As a more generic solution, you can use re.escape() to automatically escape a string so that all characters are interpreted literally. For example:

substr_to_find = '('
substr_locs = [m.start() for m in re.finditer(re.escape(substr_to_find), s)]

As pointed out by DSM in comments, in this situation you could also use a very readable list comprehension instead of regex:

openp = [i for i, c in enumerate(s) if c == "("]

Upvotes: 6

Related Questions