我想查看字串中一對括號是否與另一對括號相鄰,但是:我希望它不會在一對括號內被檢測到。(像這樣)
>>> s = "(text(some other stuff))"
>>> check_parenthesis(s)
False
>>> s = "(text)(more text)"
>>> check_parenthesis(s)
True
我嘗試過的:
>>> s = "(text)(more text)"
>>> s.find(")(") != -1 # Thing is: if i put ')(' inside a pair of parenthesis, it will return 'True' when i expect 'False' (I expect when ')(' in pair of parenthesis, it return 'False', but if it's like this: '(text)(more text)' then i expect 'True')
True
>>> s = "(text)()"
>>> s.find(")(") != -1 # Expected 'False' because ')(' is inside pair of parenthesis
True
我已經嘗試了近 30 分鐘的代碼
甚至在網上搜索
我該怎么做呢?(Debian/Ubuntu,Python-3.8.10)
uj5u.com熱心網友回復:
您的問題仍然不清楚,但是這通過了您定義的測驗。(雖然我認為沒有任何必要)
def check_parenthesis(text):
position = text.find(')(') # return the starting position of the sub-string
if (position != -1) and (position < len(text) - 2):
if text[position 2] != ")":
return True
return False
check_parenthesis('(test)()')=False
check_parenthesis('(test)(some_more)')=True
check_parenthesis('(test(some_more))')=False
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/393383.html
上一篇:粘貼兩個字串以實作所需的組合
下一篇:用一些限制替換字符
