![](/img/trans.png)
[英]Split string based on certain words and remove certain special characters in Python
[英]Splice a string based on certain characters
我正在寻找一种方法来检查字符串中的某些字符。 例如:
#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]
如果你想要“(你好+世界)”
s[s.rfind("(")+1:s.find(")")]
如果你想要“你好+世界”
您可以去除括号(如果在您的情况下,它们总是出现在字符串的开头和结尾):
>>> s= '((hello+world))'
>>> s.strip('()')
'hello+world'
另一种选择是使用正则表达式来提取双括号内的内容:
>>> re.match('\(\((.*?)\)\)', s).group(1)
'hello+world'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.