我当前的代码有效,但不是我希望它的工作方式。目前,如果我输入一个字,即“通过compc” 然后搜索字符“C” 输出将是:在Python中搜索输入字符串P2中的输入字符
'c' found at index 0
Sorry, no occurrences of 'c' found at index 1
Sorry, no occurrences of 'c' found at index 2
Sorry, no occurrences of 'c' found at index 3
'c' found at index 4
,但我想它做的是只显示:
'c' found at index 0
'c' found at index 4
如果没有找到字符,那么干脆:
Sorry, no occurrences of 'c' found
我当前的代码是:
print("This program finds all indexes of a character in a string. \n")
inStr = input("Enter a string to search:\n")
searchChar = input("\nWhat character to find? ")
searchChar = searchChar[0]
anyFound = False
startAt = 0
index = startAt
while index < len(inStr):
if inStr[index] == searchChar:
anyFound = True
if anyFound == True:
print ("'" + searchChar + "' found at index", index)
index = index + 1
anyFound = False
else:
anyFound == False
print("Sorry, no occurrences of '" + searchChar + "' found")
index = index + 1
感谢您的回复,虽然我试图找出我的代码有什么问题。尽管在for循环中它会更高效,但我试图在while循环内完成任务。有关于此的任何想法? – Xrin
你必须在'for'后面打印'Sorry ...',而不是'for'内。 – furas