if condition for value within parentheses or not python -


i know there has been many questions need small step. trying figure out way see if particular value within parenthesis or not. need store values within parenthesis negative integers otherwise positive integers. using function gives me error values not in parenthesis.

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

please help.

if want remove parentheses if present , return string representation of number without parentheses, strip() them:

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

alternatively, if want actual integers , they're stored without signs:

in [1]: def extract(s):    ...:     if s.startswith('(') , s.endswith(')'):    ...:         return -int(s[1:-1])    ...:     return int(s)    ...:   in [2]: extract('(23)') out[2]: -23  in [3]: extract('43') out[3]: 43 

Comments

Popular posts from this blog

javascript - How to synchronize the Three.js and HTML/SVG coordinate systems (especially w.r.t. the y-axis)? -

javascript - How do I find how many occurences are there of a highlighted string, and which occurence is it? -

java - Reading data from multiple zip files and combining them to one -