例如,我有一個字串需要從字串中洗掉某個關鍵字,所以可以說關鍵字是whatthemomooofun,我想從中洗掉該單詞moo,我嘗試使用 remove 函式,但它只洗掉了一次“moo”,但是現在我的字串是whatthemoofun,我似乎可以洗掉它,無論如何我可以這樣做嗎?
uj5u.com熱心網友回復:
您可以使用replace內置功能
def str_manipulate(word, key):
while key in word:
word = word.replace(key, '')
return word
uj5u.com熱心網友回復:
您是否嘗試過使用 while 回圈?您可以回圈遍歷它,直到它不再找到您的關鍵字,然后再跳出。
編輯
原因答案可以通過一個例子來改進,看看它處理的一般方法:
例子
s = 'whatthemomooofun'
while 'moo' in s:
s= s.replace('moo','')
print(s)
輸出
whatthefun
uj5u.com熱心網友回復:
original_string = "!(Hell@o)"
characters_to_remove = "!()@"
new_string = original_string
for character in characters_to_remove:
new_string = new_string.replace(character, "")
print(new_string)
輸出
Hello
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/362733.html
