問題 5
僅當句子以舊字串結尾時,該函式才用新字串替換句子中的舊字串。如果句子中的舊字串不止一次出現,則只替換末尾的那個。例如,replace_ending("abcabc", "abc", "xyz") 應該回傳 abcxyz,而不是 xyzxyz。
我的代碼:
def replace_ending(sentence, old, new):
new_sentence=''
new_sentence1=''
if old in sentence:
start_i = sentence.index(old)
oldword_length=len(old)
new_sentence1=sentence[start_i len(old):]
while old in new_sentence1:
start_i = new_sentence1.index(old)
oldword_length=len(old)
new_sentence1 = new_sentence1[start_i len(old):]
new_sentence=sentence[:start_i] new sentence[start_i len(old):]
return new_sentence
return sentence
print(replace_ending("It's raining cats and cats","cats","dogs"))
# Should display "It's raining cats and dogs"
uj5u.com熱心網友回復:
我洗掉了您的評論,并用第一個輸入向您展示了每個階段發生的情況的評論取而代之。這是您可以自己診斷代碼問題的事情,或者使用除錯器查看每個階段的每個變數的值并執行相同的操作。
def replace_ending(sentence, old, new):
# sentence = "It's raining cats and cats"
# old = "cats"
# new = "dogs"
new_sentence=''
new_sentence1=''
if old in sentence:
# "Cats" is in "It's raining cats and cats", so this code executes
start_i = sentence.index(old)
# start_i = 13
new_sentence1=sentence[start_i len(old):]
# start_i len(old) = 13 4 = 17
# new_sentence1 = sentence[17:] = "and cats"
while old in new_sentence1:
# "cats" is in "and cats", so this code executes
start_i = new_sentence1.index(old)
# start_i = 4
new_sentence1 = new_sentence1[start_i len(old):]
# new_sentence1 = new_sentence1[8:] = "" (empty string)
# "Cats is not in the empty string so the while loop finishes here"
new_sentence=sentence[:start_i] new sentence[start_i len(old):]
# new_sentence = sentence[:4] new sentence[8:] = "It's " "dogs" "ing cats and cats"
return new_sentence
return sentence
我可以看到你想要做什么以及你哪里出錯了,但這感覺就像你讓它變得非常復雜。研究內置的字串方法endswith,因為這可能會更容易。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/419858.html
標籤:
上一篇:如何從匹配條件的字串中挑選單詞
