Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a value that's inside parentheses in a string in Python? [duplicate]

Tags:

python

I've got something like this:

a = '2(3.4)'
b = '12(3.5)'

I only want the value inside the brackets. I used regex, and it worked, but my teacher won't allow it. How can I do this?

like image 908
matiit Avatar asked Nov 07 '11 18:11

matiit


2 Answers

>>> a = '2(3.4)'
>>> a[a.index("(") + 1:a.rindex(")")]
'3.4'
like image 54
Sven Marnach Avatar answered Sep 30 '22 06:09

Sven Marnach


>>> a, b = '2(3.4)', '12(3.5)'
>>> def extract(string, start='(', stop=')'):
        return string[string.index(start)+1:string.index(stop)]

>>> extract(a), extract(b)
('3.4', '3.5')
>>> 
like image 41
Noctis Skytower Avatar answered Sep 30 '22 04:09

Noctis Skytower