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

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

我正在 运行 解决通过单词列表将我的代码 运行 并列出字母在列表中的位置的问题。它可以很好地列出前两个单词的位置,但是当遇到没有指定字母的单词时,代码会跳过。我将在下面粘贴问题和我当前的代码以及当前的输出。

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.

#This program is supposed to print the location of the 'o' #in each word in the list. However, line 22 causes an #error if 'o' is not in the word. Add try/except blocks #to print "Not found" when the word does not have an 'o'. #However, when the current word does not have an 'o', the #program should continue to behave as it does now.

#Hint: don't worry that you don't know how line 18 works. #All you need to know is that it may cause an error.

#You may not use any conditionals.

#Fix this code!

我的代码

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

输出

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

你只需要像这样添加 try-except 块:

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

使用 try 和 except 块来获取字母在单词中的位置。

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