1

I know there has been many questions about this already but I just need a small step. I am trying to figure out a way to see if a particular value is within parenthesis or not. I need to store values within parenthesis as negative integers otherwise positive integers. I am using this function but it gives me error for values which are not in parenthesis.

    def extract(string, start='(', stop=')'):
         return string[string.index(start)+1:string.index(stop)]

Please help.

Kunj
  • 77
  • 9
  • possible duplicate of [Convert a number enclosed in parentheses (string) to a negative integer (or float) using Python?](http://stackoverflow.com/questions/16718648/convert-a-number-enclosed-in-parentheses-string-to-a-negative-integer-or-floa) – Ignacio Vazquez-Abrams Dec 06 '14 at 02:16

1 Answers1

1

If you simply want to remove the parentheses if they are present and return string representation of the number without parentheses, just strip() them:

>>> a = '(-23)'
>>> b = '43'
>>> a.strip('(').strip(')')
'-23'

>>> b.strip('(').strip(')')
'43'

Alternatively, if you want the actual integers and they're stored without signs:

In [1]: def extract(s):
   ...:     if s.startswith('(') and s.endswith(')'):
   ...:         return -int(s[1:-1])
   ...:     return int(s)
   ...: 

In [2]: extract('(23)')
Out[2]: -23

In [3]: extract('43')
Out[3]: 43
xnx
  • 24,509
  • 11
  • 70
  • 109