Python 用于查找字符串中字符索引的If-else语句
由于某些原因,如果没有else语句,代码将查找字符串中字符的索引。但是,当我添加else语句来声明是否找不到字符时。它所做的就是给我else语句,即使字符在字符串中Python 用于查找字符串中字符索引的If-else语句,python,string,python-3.x,indexing,character,Python,String,Python 3.x,Indexing,Character,由于某些原因,如果没有else语句,代码将查找字符串中字符的索引。但是,当我添加else语句来声明是否找不到字符时。它所做的就是给我else语句,即使字符在字符串中 #Function takes a character and a string and returns the index of the character #found in the string. def whereIsItS(letter, word): #Start finding the index of cha
#Function takes a character and a string and returns the index of the character
#found in the string.
def whereIsItS(letter, word):
#Start finding the index of characters in the string starting at 0.
letInWord = 0
#For loop to find specific characters in a string.
for l in word:
#If the letter is found it returns the index of the letter.
if l == letter:
#Moves to the next character in the string.
letInWord += 1
else:
return "It is not there."
#Returns the index of the character found the string.
return word.index(letter)
我似乎无法理解为什么它在没有else语句的情况下工作,而在else语句的情况下工作。您正在
else
条件下返回函数。
更改
返回“它不在那里。”
到打印(“它不在那里”)
这是有问题的代码:
for l in word:
#If the letter is found it returns the index of the letter.
if l == letter:
#Moves to the next character in the string.
letInWord += 1
else:
# You end the loop here
# return "It is not there."
# try this:
print("It is not there.")
如您所见,<代码>返回<代码>在循环的中间退出函数。如果不想离开for循环,应该使用
print()
请记住,您可以只使用word.index(letter)
,而不需要像这样的整个for循环:
def whereIsItS(letter, word):
try:
return word.index(letter)
except ValueError:
print("letter not in string")
return
将始终退出函数,而不会继续执行任何循环
您可以打印它不在那里,但这甚至不是真的,因为您正在打印当前的字母
通过以下几点可以相对简单地实现这一点:
def whereIsItS(letter, word):
if letter in word:
return word.index(letter)
else:
return "Letter {0} not in word {1}".format(letter, word)
如果字母在单词中,则返回其索引;如果不是,则返回指定未找到该字母的消息
使用条件表达式进一步修剪,以:
def whereIsItS(letter, word):
return word.index(letter) if letter in word else "Letter {0} not in word {1}".format(letter, word)
我和其他人已经在其他答案中解释了您的错误
现在,让我们避免使用无效代码。这里有三种有效的方法
(仍然是
使用enumerate
获取索引和值。第一次出现:您可以返回索引
代码:
尝试index
并捕获异常(您的预检查似乎是为了避免此异常)
代码:
使用str.find
。它查找子字符串,因此也可以查找唯一的字母(与不同,index
不抛出异常,只返回-1
)
代码:
当然,当字母不在这里时的返回值实际上是不实用的。我会选择-1
(比如find
)或者None
,因为如果单词的第一个字母不是必需的字母,它会立即返回I。您可以更好地计算索引。我想您希望避免index
返回的异常。您的函数有11行代码(我计算过!)这是毫无意义的,然后它从内置的index
方法返回结果。为什么?我还处于编程的初级阶段,我想我必须通过字符串中的字符进行for循环计数才能获得索引。我才在两周前开始>。You if else语句对我有效。非常感谢。:)我对print有一个问题,因为它会重复打印字符串多次,直到到达目标字符串的末尾。这与Jim的解释一起帮助了我。非常感谢。:)我在操作员中多次重复打印时遇到问题(可能是因为for循环)。你们是最好的。感谢您的帮助和快速回复。:)
def whereIsItS(letter, word):
#Start finding the index of characters in the string starting at 0.
#For loop to find specific characters in a string.
for i,l in enumerate(word):
#If the letter is found it returns the index of the letter.
if l == letter:
return i
return "It is not there."
def whereIsItS(letter, word):
try:
return word.index(letter)
except ValueError:
return "It is not there."
def whereIsItS(letter, word):
idx = word.find(letter)
if idx>=0:
return idx
else:
return "It is not there."