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

时间:2015-11-13 17:50:39

标签: python

我当前的代码有效,但不是我希望它如何工作。目前,如果我输入一个单词,即" 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

4 个答案:

答案 0 :(得分: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))

答案 1 :(得分:0)

更改你的while循环结构:

anyFound = False #initialize as False
while index < len(inStr):
    if inStr[index] == searchChar:
        print ("'" + searchChar + "' found at index", index)
        anyFound = True #will change if any are found
    #don't do anything if the char is not the same
    index = index + 1

#following code will only run if anyFound wasn't changed
if not anyFound: 
    print("Sorry, no occurrences of '" + searchChar + "' found")

答案 2 :(得分:0)

您的代码存在一些问题,这似乎解决了Python 2的所有问题:

#!/usr/bin/env python
print("This program finds all indexes of a character in a string. \n")
inStr = raw_input("Enter a string to search:\n")
searchChar = raw_input("\nWhat character to find? ")
searchChar = searchChar[0]
anyFound = False
startAt = 0
index = startAt
while index < len(inStr):
    if inStr[index] == searchChar:
        anyFound = True
        print "'" + searchChar + "' found at index " + str(index)
        index = index + 1
    index += 1
if not anyFound:
    print("Sorry, no occurrences of '" + searchChar + "' found")

我所做的改进是:

  1. 使用raw_input代替input,因此用户只需键入abca而不是"abca"
  2. 移动最后一张支票

答案 3 :(得分:0)

我将您的anyFound布尔值移到外面,只有在您找到某些内容后才设置它。除了我带出的索引增量之外,我保留了其他所有内容与你所拥有的相似。

anyFound = False
while index < len(inStr): 

    if inStr[index] == searchChar:
        print ("'" + searchChar + "' found at index", index)
        anyFound = True

    index = index + 1

if not anyFound:
    print("Sorry, no occurrences of '" + searchChar + "' found")