简体   繁体   中英

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.

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]

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.

>>> 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM