[英]How can i remove only the last bracket from a string in python?
如何只從字符串中刪除最后一個括號?
例如,輸入 1:
"hell(h)o(world)"
我想要這個結果:
"hell(h)o"
輸入 2 :-
hel(lo(wor)ld)
我想要 :-
hel
如您所見,中間括號保持完整,只有最后一個括號被移除。
我試過了 :-
import re
string = 'hell(h)o(world)'
print(re.sub('[()]', '', string))
輸出 :-
hellhoworld
我想出了一個解決方案:-
我是這樣做的
string = 'hell(h)o(world)'
if (string[-1] == ")"):
add=int(string.rfind('(', 0))
print(string[:add])
輸出 :-
hell(h)o
尋找其他優化的解決方案/建議..
如果這有用,請參閱下面的內容,讓我知道我會進一步優化。
string = 'hell(h)o(world)'
count=0
r=''
for i in reversed(string):
if count <2 and (i == ')' or i=='('):
count+=1
pass
else:
r+=i
for i in reversed(r):
print(i, end='')
如果您想從字符串中刪除最后一個括號,即使它不在字符串的末尾,您可以嘗試這樣的操作。 只有當您知道在字符串中某處有一個以括號開頭和結尾的子字符串時,這才有效,因此您可能需要對此進行某種檢查。 如果您正在處理嵌套括號,您還需要進行修改。
str = "hell(h)o(world)"
r_str = str[::-1] # creates reverse copy of string
for i in range(len(str)):
if r_str[i] == ")":
start = i
elif r_str[i] == "(":
end = i+1
break
x = r_str[start:end][::-1] # substring that we want to remove
str = str.replace(x,'')
print(str)
輸出:
hell(h)o
如果字符串不在末尾:
str = "hell(h)o(world)blahblahblah"
輸出:
hell(h)oblahblahblah
編輯:這是檢測嵌套括號的修改版本。 但是,請記住,如果字符串中有不平衡的括號,這將不起作用。
str = "hell(h)o(w(orld))"
r_str = str[::-1]
p_count = 0
for i in range(len(str)):
if r_str[i] == ")":
if p_count == 0:
start = i
p_count = p_count+1
elif r_str[i] == "(":
if p_count == 1:
end = i+1
break
else:
p_count = p_count - 1
x = r_str[start:end][::-1]
print("x:", x)
str = str.replace(x,'')
print(str)
輸出:
hell(h)o
像這樣的東西?
string = 'hell(h)o(w(orl)d)23'
new_str = ''
escaped = 0
for char in reversed(string):
if escaped is not None and char == ')':
escaped += 1
if not escaped:
new_str = char + new_str
if escaped is not None and char == '(':
escaped -= 1
if escaped == 0:
escaped = None
print(new_str)
這在 a )
時開始轉義,並在其當前級別用(
關閉時停止。因此嵌套()
不會影響它。
使用re.sub('[()]', '', string)
將用空字符串替換re.sub('[()]', '', string)
任何括號。
為了匹配最后一組平衡括號,並且如果您可以使用正則表達式PyPi 模塊,您可以使用重復第一個子組的遞歸模式,並斷言在右側不再出現(
或)
(\((?:[^()\n]++|(?1))*\))(?=[^()\n]*$)
模式匹配:
(
捕獲組 1
\\(
匹配(
(?:[^()\\n]++|(?1))*
重復 0+ 次匹配除(
)
或換行符以外的任何字符。 如果這樣做,請使用(?1)
遞歸第 1 組\\)
匹配)
)
關閉第 1 組(?=[^()\\n]*$)
正向前瞻,斷言直到字符串結尾沒有(
或)
或換行符例如
import regex
strings = [
"hell(h)o(world)",
"hel(lo(wor)ld)",
"hell(h)o(world)blahblahblah"
]
pattern = r"(\((?:[^()]++|(?1))*\))(?=[^()]*$)"
for s in strings:
print(regex.sub(pattern, "", s))
輸出
hell(h)o
hel
hell(h)oblahblahblah
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.