3 回答

TA貢獻1921條經(jīng)驗 獲得超9個贊
字符串不支持項目刪除。您必須創(chuàng)建一個新字符串。
>>> astring = 'abc->def'
>>> astring.index('->') # Look at the index of the target string
3
>>> x=3
>>> astring[x:x+3] # Here is the slice you want to remove
'->d'
>>> astring[0:x] + astring[x+3:] # Here is a copy of the string before and after, but not including the slice
'abcef'
這僅處理每個字符串一個“->”,但您可以對其進行迭代。

TA貢獻2012條經(jīng)驗 獲得超12個贊
這是一個簡單的遞歸解決方案 -
# Constant storing the length of the arrow
ARROW_LEN = len('->')
def delete_forward(s: str):
try:
first_occurence = s.index('->')
except ValueError:
# No more arrows in string
return s
if s[first_occurence + ARROW_LEN:first_occurence + ARROW_LEN + ARROW_LEN] == '->':
# Don't delete part of the next arrow
next_s = s[first_occurence + ARROW_LEN:]
else:
# Delete the character immediately following the arrow
next_s = s[first_occurence + ARROW_LEN + 1:]
return delete_forward(s[:first_occurence] + s[first_occurence + ARROW_LEN + 1:])
請記住,Python 字符串是不可變的,因此您應(yīng)該依賴字符串切片來創(chuàng)建新字符串。
在每個遞歸步驟中,都會找到 的第一個索引->,并提取出在此之前的所有內(nèi)容。然后,檢查當(dāng)前位置后是否有另一個->緊隨其后的字符 - 如果有,請勿刪除下一個字符并delete_forward在第一次出現(xiàn)后調(diào)用所有內(nèi)容。如果緊隨其后的不是箭頭,則刪除當(dāng)前箭頭之后緊鄰的下一個字符,并將其送入delete_forward。
這將x->zb變成xb.
遞歸的基本情況是.index找不到匹配項,在這種情況下返回結(jié)果字符串。
輸出
>>> delete_forward('ab->cz')
'abz'
>>> delete_forward('abcz')
'abcz'
>>> delete_forward('->abc->z')
'bc'
>>> delete_forward('abc->z->')
'abc'
>>> delete_forward('a-->b>x-->c>de->f->->g->->->->->')
'a->x->de'

TA貢獻1785條經(jīng)驗 獲得超8個贊
在 python 中可以有多種方法來實現(xiàn)這一點,例如:
使用拆分和列表推導(dǎo)式(如果您想在每次遇到一個或多個刪除字符時刪除單個字符):
def delete_forward(s):
return ''.join([s.split('->')[0]] + [i[1:] if len(i)>1 else "" for i in s.split('->')[1:]])
現(xiàn)在delete_forward("a->bcz")返回'acz'&delete_forward("->x->z")返回''。請注意,這適用于每種可能的情況,無論是否有許多刪除字符,一個或根本沒有。此外,只要輸入是,它就永遠不會拋出任何異?;蝈e誤str。然而,這假設(shè)您每次遇到一個或多個刪除字符時都希望刪除單個字符。
如果要刪除與刪除字符發(fā)生次數(shù)一樣多的字符:
def delete_forward(s):
new_str =''
start = 0
for end in [i for i in range(len(s)) if s.startswith('->', i)] +[len(s)+1]:
new_str += s[start:end]
count = 0
start = max(start, end)
while s[start:start+2] =='->':
count+=1
start+=2
start += count
return new_str
對于上述兩種情況,這會產(chǎn)生相同的輸出,但是對于 case: 'a->->bc',它會產(chǎn)生'a'而不是'ac'第一個函數(shù)產(chǎn)生的輸出。
添加回答
舉報