根据某些字符拼接字符串



我正在寻找一种方法来检查字符串中的某些字符。例如:

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

基本上我想让程序从第二次出现的(开始,然后从那里开始拼接,直到它遇到第一次出现的)。然后我可以把它返回到另一个函数或者别的什么。有解决方案吗?

你可以这样做:(假设你想要最里面的括号)

s[s.rfind("("):s.find(")")+1]如果你想"(hello+world)"

s[s.rfind("(")+1:s.find(")")]如果你想要"hello+world"

您可以去掉括号(如果在您的情况下,它们总是出现在字符串的开头和结尾):

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

另一个选择是使用正则表达式来提取双括号内的内容:

>>> re.match('(((.*?)))', s).group(1)
'hello+world'

最新更新