Question

I'm looking for a way to examine only certain characters within a string. For example:

#Given the string
s= '((hello+world))'
s[1:')'] #This obviously doesn't work because you can only splice a string using ints

Basically I want the program to start at the second occurence of ( and then from there splice until it hits the first occurence of ). So then maybe from there I can return it to another fucntion or whatever. Any solutions?

Était-ce utile?

La solution

You can do it as follows: (assuming you want the innermost parenthesis)

s[s.rfind("("):s.find(")")+1] if you want "(hello+world)"

s[s.rfind("(")+1:s.find(")")] if you want "hello+world"

Autres conseils

You can strip parenthesis (if, in your case, they always appear at the beginning and the end of the string):

>>> s= '((hello+world))'
>>> s.strip('()')
'hello+world'

Another option is to use regular expression to extract what is inside the double parenthesis:

>>> re.match('\(\((.*?)\)\)', s).group(1)
'hello+world'
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top