How can I get the parenthesis numbers of a string in Python 3x

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

Answers (1)

j3r3mias
j3r3mias

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:

state machine

PS: I change the name str to s because str is a definition for the type string in python.

Upvotes: 1

Related Questions