Raj
Raj

Reputation: 3462

Python parsing integers inside parantheses in a string

I want to parse a simple string with python as -

Limits paramA : (7, 45) paramB : (0, 0) paramC : (1, 23)

I want to extract 7, 45, 0, 0, 1, 23 in different integers. Could someone tell me how can I extract this?

There are lot of string parsing questions in the forum, but I am not able to find the answer that suits me best.

Thank You.

Upvotes: 2

Views: 140

Answers (3)

Lanaru
Lanaru

Reputation: 9721

>>> import re
>>> import ast

>>> nums = [num for tup in [ast.literal_eval(tup) for tup in re.findall('\([^)]*\)', s)] for num in tup]
[7, 45, 0, 0, 1, 23]

Only extracts numbers inside parentheses.

Upvotes: 2

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250961

using regex:

In [71]: import re

In [72]: strs="Limits paramA : (7, 45) paramB : (0, 0) paramC : (1, 23)"

In [74]: [int(digit) for digit in re.findall(r'\d+',strs)]
Out[74]: [7, 45, 0, 0, 1, 23]

Upvotes: 6

Andrew Clark
Andrew Clark

Reputation: 208475

If you just want all numbers in the string:

>>> import re
>>> s = 'Limits paramA : (7, 45) paramB : (0, 0) paramC : (1, 23)'
>>> [int(n) for n in re.findall(r'\d+', s)]
[7, 45, 0, 0, 1, 23]

If you only want to find numbers within parentheses (same result in this case):

>>> [int(n) for m in re.findall(r'\(([\d, ]+)\)', s) for n in m.split(',')]
[7, 45, 0, 0, 1, 23]

Here is an example of where this difference might be important:

>>> s = 'Limits param1 : (7, 45) param2 : (0, 0) param3 : (1, 23)'
>>> [int(n) for n in re.findall(r'\d+', s)]
[1, 7, 45, 2, 0, 0, 3, 1, 23]
>>> [int(n) for m in re.findall(r'\(([\d, ]+)\)', s) for n in m.split(',')]
[7, 45, 0, 0, 1, 23]

Note that the first method also matches the 1 from param1 and the 2 from param2, etc.

Upvotes: 2

Related Questions