2015-11-11 255 views
0

該腳本的目的是允許用戶輸入一個單詞並輸入他們希望在字符串中找到的字符。然後它會查找所有的出現並輸出索引的位置。 我目前的腳本運行良好,所以沒有語法錯誤,但是當我輸入一個字符時,它什麼也不做。 我的代碼:在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.

+0

考慮何時會達到'index = index + 1'(嘗試在您的腦海中,在紙上或使用例如http://www.pythontutor.com逐行代碼)。 – jonrsharpe

+0

由於索引從0開始,並且在向其添加1之後返回索引。 – Kasramvd

+0

提示:正如@jonrsharpe所寫。你的評論「什麼都不做」應該是:「它在while循環中無休止地循環,索引永遠保持爲0」。 –

回答

1

有兩個問題與您的代碼:

  1. 您的縮進在index=index+1之後關閉。
  2. 您錯過found=True行後的break聲明。

另外,你爲什麼要重新實現內置於find方法的字符串。 string.find(char)會完成這個相同的任務。

不需要比較布爾值爲TrueFalseif found:if not found:將工作intead。

+0

我明白了,現在雖然我找到了字符串,但它只是打印字符串中找到的第一個字符。我將如何打印該字符串中的所有字符? – Xrin