根据特定字符分割字符串
我想找一种方法,只检查字符串中的某些字符。比如说:
#Given the string
s= '((hello+world))'
s[1:')'] #This obviously doesn't work because you can only splice a string using ints
简单来说,我希望程序从第二个出现的 (
开始,然后一直切割到第一个出现的 )
。这样的话,我就可以把结果传给另一个函数或者做其他事情。有没有什么解决办法?
2 个回答
1
你可以用strip方法去掉字符串开头和结尾的括号(前提是这些括号总是出现在字符串的最前面和最后面):
>>> s= '((hello+world))'
>>> s.strip('()')
'hello+world'
另一种选择是使用正则表达式来提取双括号里面的内容:
>>> re.match('\(\((.*?)\)\)', s).group(1)
'hello+world'
1
你可以这样做:(假设你想要最里面的括号内容)
s[s.rfind("("):s.find(")")+1]
如果你想要的是 "(hello+world)"
s[s.rfind("(")+1:s.find(")")]
如果你想要的是 "hello+world"