我需要撰寫程式,列印出所有至少三個字符長的子字串,并以用戶指定的字符開頭。這是它應該如何作業的示例:
Please type in a word: mammoth
Please type in a character: m
mam
mmo
mot
我的代碼看起來像這樣,它不能正常作業(它只顯示 1 個子字串):
word = word = input("Please type in a word: ")
character = input("Please type in a character: ")
index = word.find(character)
while True:
if index!=-1 and len(word)>=index 3:
print(word[index:index 3])
break
uj5u.com熱心網友回復:
你剛剛開始了一個無限的 while 回圈并在第一場比賽中停止
您可以將其修改為:
word = word = input("Please type in a word: ")
character = input("Please type in a character: ")
index = word.find(character)
while index!=-1:
if len(word)>=index 3:
print(word[index:index 3])
index = word.find(character,index 1)
uj5u.com熱心網友回復:
進入if. 如果找到這樣的子字串,回圈將只回圈一次(如您所見)。如果沒有這樣的子字串,它將無限回圈,并且不列印任何內容。
相反,您應該將條件移動到回圈本身,并繼續更新index:
while index != -1 and len(word) >= index 3:
print(word[index:index 3])
index = word.find(character, index 1)
uj5u.com熱心網友回復:
find 僅回傳第一次出現,因此回圈自己可能更容易:
word = 'mammoth'
character = 'm'
for x in range(0, len(word) - 2):
substr = word[x:x 3]
if substr.startswith(character):
print(substr)
出去:
mam
mmo
mot
uj5u.com熱心網友回復:
再會,
為了實作這一點,您必須構建一個演算法。構建解決此問題的演算法的一種方法是遍歷字串中的所有字符,并注意字串是 Python 中的可迭代物件,檢查與提供的字符是否匹配,然后檢查該字符是否至少有 2 個前導字符,如果是,則列印結果并繼續,直到字串只剩下 2 個字符為止。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/336988.html
