jeudi 16 juin 2016

Verify how many pair of parentheses exist in a string in Python

I'm wondering if there's any way to find how many pair of parentheses are in a string.

I have to do some string manipulation and I sometimes have something like:

some_string = '1.8.0*99(0000000*kWh)'

or something like

some_string = '1.6.1*01(007.717*kW)(1604041815)'

What I'd like to do is:

  • get all the digits between the parentheses (e.g for the first string: 0000000)
  • if there are 2 pairs of parentheses (there will always be max 2 pairs) get all the digits and join them (e.g for the second string I'll have: 0077171604041815)

How can I verify how many pair of parentheses are in a string so that I can do later something like:

if number_of_pairs == 1:
    do_this
else:
    do_that

Or maybe there's an easier way to do what I want but couldn't think of one so far.

I know how to get only the digits in a string: final_string = re.sub('[^0-9]', '', my_string), but I'm wondering how could I treat both cases.

Aucun commentaire:

Enregistrer un commentaire