我正在處理的一個問題涉及使用 while 回圈遍歷字串,使用 Find() 函式在該字串出現時回傳該字串中特定單詞的索引。對于此示例,它在包含整個 The Time Machine 的字串變數中查找名稱“Weena”。我被要求專門使用 while 回圈和 Find() 函式,盡管我已經使用列舉器解決了這個問題。
for count, word in enumerate(time_machine_text.split()):
if 'Weena' in word:
print(count)
我習慣于 foreach 回圈,因為我在學習 C# 時非常依賴它們,所以我看到的每個回圈問題我都默認使用 foreach 回圈。任何滿足使用 while 回圈和 Find() 函式的任務要求的建議將不勝感激。
uj5u.com熱心網友回復:
我會count單獨初始化變數并使用 while 回圈遍歷time_machine_text.split(). 例如:
count = 0
words = time_machine_text.split()
while count < len(words):
word = words[count]
if "weena" in word:
print(count)
count = 1
編輯:這是使用 find() 函式的版本
count = 0
words = time_machine_text.split()
while count < len(words):
word = words[count]
if word.find("weena") != -1:
print(count)
count = 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/473819.html
