문제

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?

도움이 되었습니까?

해결책

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"

다른 팁

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'
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top