该脚本的目的是允许用户输入单词并输入他们希望在字符串中找到的字符。然后它将找到所有出现并输出索引的位置。 我当前的脚本运行正常所以没有语法错误,但是当我输入一个字符时,它什么也没做。 我的代码:
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 :(得分:1)
您的代码有两个问题:
index=index+1
中删除。break
行之后缺少found=True
语句。另外,为什么要在字符串上重新实现内置的find
方法。 string.find(char)
将完成同样的任务。
没有必要将布尔值与True
和False
进行比较。 <{1}}和if found:
可以使用。