Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python3中的错误处理-在单词列表中查找特定字母的位置_Python_Python 3.x_List_Error Handling_Letter - Fatal编程技术网

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

Python3中的错误处理-在单词列表中查找特定字母的位置,python,python-3.x,list,error-handling,letter,Python,Python 3.x,List,Error Handling,Letter,我遇到了让我的代码在单词列表中运行并在列表中列出字母位置的问题。它在列出前两个单词的位置时效果很好,但是当它遇到没有指定字母的单词时,代码会跳过。我将把问题和我当前的代码以及当前的输出粘贴到下面 单词=[“狗”、“麻雀”、“猫”、“青蛙”] #您可以修改上面的代码行,但不要移动它们! #当您提交代码时,我们会将这些行更改为 #为变量指定不同的值 #此程序应打印“o”的位置 #在列表中的每个单词中。但是,第22行会导致 #如果单词中没有“o”,则出错。添加try/except块 #当单词没有“o”

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

单词=[“狗”、“麻雀”、“猫”、“青蛙”]

#您可以修改上面的代码行,但不要移动它们! #当您提交代码时,我们会将这些行更改为 #为变量指定不同的值

#此程序应打印“o”的位置 #在列表中的每个单词中。但是,第22行会导致 #如果单词中没有“o”,则出错。添加try/except块 #当单词没有“o”时打印“未找到”。 #但是,当当前单词没有“o”时 #程序应该继续像现在这样运行

#提示:不要担心您不知道第18行是如何工作的。 #您需要知道的是,它可能会导致错误

#你不能使用任何条件句

#修正这个代码

我的代码

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
1
5.
回溯(最近一次呼叫最后一次):
文件“FindingO.py”,第22行,在
打印(字索引(“o”))
ValueError:未找到子字符串
命令以非零状态1退出

您只需添加以下try-except块:

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

您只需添加以下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

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

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

那不是你的密码。这是作业/测验题的代码。对不起,我已经有了代码。我很高兴粘贴我尝试过的所有不同的东西,尽管我不相信这会有帮助,因为我似乎无法使用except将其返回到开头。在调用
.index
之前检查单词中是否有“o”。或者使用
try:
探索,但这不是您的代码。这是作业/测验题的代码。对不起,我已经有了代码。我很高兴粘贴我尝试过的所有不同的东西,尽管我不相信这会有帮助,因为我似乎无法使用except将其返回到开头。在调用
.index
或使用
try:
探索之前,请检查单词中是否有“o”。非常感谢,每当我尝试除块时,我都会错过pass这个词非常感谢,每当我尝试除块缩进错误缩进错误时,我都会错过pass这个词