該腳本的目的是允許用戶輸入一個單詞並輸入他們希望在字符串中找到的字符。然後它會查找所有的出現並輸出索引的位置。 我目前的腳本運行良好,所以沒有語法錯誤,但是當我輸入一個字符時,它什麼也不做。 我的代碼:在Python中輸入字符串中搜索輸入字符
print("This program finds all indexes of a character in a string. \n")
string = input("Enter a string to search:\n")
char = input("\nWhat character to find? ")
char = char[0]
found = False
start = 0
index = start
while index < len(string):
if string[index] == char:
found = True
index = index + 1
if found == True:
print ("'" + char + "' found at index", index)
if found == False:
print("Sorry, no occurrences of '" + char + "' found")
哪裏出問題了?爲了不打印出我的角色。奇怪的是,當我輸入字符串的單個字符時,即兩個輸入的「c」,它表示索引是1,當它應該是0.
考慮何時會達到'index = index + 1'(嘗試在您的腦海中,在紙上或使用例如http://www.pythontutor.com逐行代碼)。 – jonrsharpe
由於索引從0開始,並且在向其添加1之後返回索引。 – Kasramvd
提示:正如@jonrsharpe所寫。你的評論「什麼都不做」應該是:「它在while循環中無休止地循環,索引永遠保持爲0」。 –