gpt4 book ai didi

python - 在Python中搜索输入字符串P2中的输入字符

转载 作者:太空宇宙 更新时间:2023-11-03 17:15:31 25 4
gpt4 key购买 nike

我当前的代码可以工作,但不是我想要的工作方式。目前,如果我输入一个单词,即“compc”然后搜索字符“c”输出将是:

'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

最佳答案

print("This program finds all indexes of a character in a string. \n")

in_str = input("Enter a string to search:\n")
search_char = input("\nWhat character to find? ")
search_char = search_char[0]

any_found = False

for index, char in enumerate(in_str):
if char == search_char:
print("'%s' found at index %d" % (search_char, index))
any_found = True

if not any_found:
print("Sorry, no occurrences of '%s' found" % (search_char))

关于python - 在Python中搜索输入字符串P2中的输入字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33698894/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com