该脚本的目的是允许用户输入一个单词并输入他们希望在字符串中找到的字符。然后它会查找所有的出现并输出索引的位置。 我目前的脚本运行良好,所以没有语法错误,但是当我输入一个字符时,它什么也不做。 我的代码:在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”。 –