简体   繁体   English

Python3 中的错误处理 - 在单词列表中查找特定字母的位置

[英]Error Handling in Python3 - Finding location of specific letters in a list of words

I am running into issues getting my code to run through a list of words and list the location of the letters in the list.我遇到了让我的代码遍历单词列表并列出列表中字母位置的问题。 It works fine in listing location for the first two words, but when it encounters a word without the specified letter, the code skips.它在前两个单词的列表位置中工作正常,但是当遇到没有指定字母的单词时,代码会跳过。 I will paste the problem and my current code as well as current output below.我将在下面粘贴问题和我当前的代码以及当前的 output。

words = ["dog", "sparrow", "cat", "frog"]词= [“狗”,“麻雀”,“猫”,“青蛙”]

#You may modify the lines of code above, but don't move them, #When you Submit your code. #您可以修改上面的代码行,但不要移动它们,#当您提交代码时。 we'll change these lines to #assign different values to the variables.我们将更改这些行以#assign 不同的值给变量。

#This program is supposed to print the location of the 'o' #in each word in the list. #这个程序应该在列表中的每个单词中打印'o'的位置。 However, line 22 causes an #error if 'o' is not in the word.但是,如果单词中没有 'o',第 22 行会导致 #error。 Add try/except blocks #to print "Not found" when the word does not have an 'o'.添加 try/except 块#以在单词没有“o”时打印“未找到”。 #However, when the current word does not have an 'o', the #program should continue to behave as it does now. #但是,当当前单词没有“o”时,#program 应该继续像现在一样运行。

#Hint: don't worry that you don't know how line 18 works. #提示:不要担心你不知道第 18 行是如何工作的。 #All you need to know is that it may cause an error. #所有你需要知道的是它可能会导致错误。

#You may not use any conditionals. #你不能使用任何条件。

#Fix this code! #修复此代码!

My Code我的代码

for word in words:
print(word.index("o"))

Output Output

1
5
Traceback (most recent call last):
  File "FindingO.py", line 22, in <module>
    print(word.index("o"))
ValueError: substring not found
Command exited with non-zero status 1

You only need to add try-except block like this:您只需要像这样添加 try-except 块:

words = ["dog", "sparrow", "cat", "frog"]
for word in words:
    try:
        print(word.index('o'))
    except:
        print("Not found")
        pass

Use try and except block to get the position of letters in the word.使用 try 和 except 块来获取单词中字母的 position。

for letter in words:
try:
    print(letter.index("o"))
except:
    print("not found")
    pass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM