How can I check if a string contains a number between two brackets and return the location?

Viewed 3843

Say I have str = "qwop(8) 5" and I want to return the position of 8.

I have the following solution:

import re

str = "qwop(8) 5"
regex = re.compile("\(\d\)")
match = re.search(regex, string) # match object has span = (4, 7)
print(match.span()[0] + 1)       # +1 gets at the number 8 rather than the first bracket

This seems really messy. Is there a more sophisticated solution? Preferably using re as I've already imported that for other uses.

3 Answers
import re

s = "qwop(8)(9) 5"
regex = re.compile("\(\d\)")
match = re.search(regex, s)
print(match.start() + 1)

start() means the start index, re.search search for the first occurrence. so this will only show the index of (8).

Related