【问题标题】:Searching for a input character in an input string in Python在 Python 中的输入字符串中搜索输入字符
【发布时间】:2015-11-11 14:49:08
【问题描述】:

脚本的目的是允许用户输入一个单词并输入一个他们希望在字符串中找到的字符。然后它将查找所有出现并输出索引的位置。 我当前的脚本运行良好,因此没有语法错误,但是当我输入一个字符时,它什么也不做。 我的代码:

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。

【问题讨论】:

  • 想想index = index + 1 何时到达(尝试在脑海中逐行遍历代码,在纸上或使用例如pythontutor.com)。
  • 因为索引从 0 开始,你在给它加 1 后返回索引。
  • 提示:正如@jonrsharpe 所写。你的评论“什么都不做”应该是:“它在while循环中无限循环,索引永远停留在0”。

标签: python


【解决方案1】:

你的代码有两个问题:

  1. index=index+1 中的缩进已关闭。
  2. 您在found=True 行之后缺少break 语句。

另外,你为什么要在字符串上重新实现内置的find 方法。 string.find(char) 将完成同样的任务。

没有必要将布尔值与TrueFalse 进行比较。 if found:if not found: 可以使用。

【讨论】:

  • 我明白了,现在虽然我找到了字符串,但它只打印了字符串中找到的第一个字符。我将如何打印该字符串中的所有字符?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 2018-04-07
  • 2019-11-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多