2015-11-11 47 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