Reputation: 43
I am trying to extract only the numbers that are inside parentheses (), but I have only been able to obtain those that are outside, does anyone know what I am doing wrong?
str = "h (3110), 23 cat 444.4 rabbit 11 2 dog (500)"
[int(s) for s in str.split() if s.isdigit()]
Regards, Thank
Upvotes: 0
Views: 96
Reputation: 371
Try to use a lib for regex called re
. It will helps you to find only the digits between parenthesis that you want.
Answer:
import re
s = "h (3110), 23 cat 444.4 rabbit 11 2 dog (500)"
l = list(map(int, re.findall(r'\((\d+)\)', s)))
print(l)
The regex \((\d+)\)
creates a group with all digits that appears between parenthesis like that:
PS: I change the name str
to s
because str
is a definition for the type string
in python.
Upvotes: 1