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

时间:2015-11-11 14:49:08

标签: 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时。

1 个答案:

答案 0 :(得分:1)

您的代码有两个问题:

  1. 您的缩进已在index=index+1中删除。
  2. 您在break行之后缺少found=True语句。
  3. 另外,为什么要在字符串上重新实现内置的find方法。 string.find(char)将完成同样的任务。

    没有必要将布尔值与TrueFalse进行比较。 <{1}}和if found:可以使用。