如何修复builtins.ValueError:找不到子字符串

时间:2017-10-01 05:03:53

标签: python python-3.x

puzzle game< - 这就是图片。 我得到ValueError一些输入。有人可以帮我解决吗?

def update_letter_view(puzzle: str, view: str, index: int, letter: str) -> str:

>>>"""Return a single character string representing the next view of the 
character at the given index.If the character at that index
of the puzzle matches the guess, then return that character. Otherwise, 
return the character at that index of the view.

>>>update_letter_view('chicken', 'ch^^ken', 2, 'i')
'i'
>>>update_letter_view('banana', 'b^n^n^', 1,'t')
'^'
"""
symbol = '^'
if letter in puzzle:
    return puzzle[puzzle.index(letter, index)]
return symbol

3 个答案:

答案 0 :(得分:1)

string.index(s, sub[, start[, end]])
     

与find()类似,但引发 ValueError when the substring is not found

这是您ValueError发生的地方。要解决此问题,请使用try/except

def update_letter_view(puzzle: str, view: str, index: int, letter: str) -> str:
   symbol = '^']

   try:
      if letter in puzzle:
         return puzzle[puzzle.index(letter, index)]
   except:
      #do something else

   return symbol

你可能会说你正在做if letter in puzzle,所以错误永远不会发生。但是,index(letter,**index**)更改了内容,因为搜索开始的起始索引可能不包含该字母。

例如:

   >>> puzzle="abcdef"
   >>> puzzle.index('c')
   =>  2
   >>> puzzle.index('c', 5)                    #beg=5 here
   =>  Traceback (most recent call last):
       File "python", line 1, in <module>
       ValueError: substring not found

答案 1 :(得分:0)

str.index如果找不到您要查找的值,则会引发ValueError。如果您的字符串是'orange'并且您在索引2之后查找“o”,则in测试将成功,但return语句将失败。

答案 2 :(得分:0)

让我们看一下python str.index()方法:

str.index(str, beg=0 end=len(string))

在您的函数中,puzzle.index(letter, index)会找到位置index的字母,所以如果letter出现在index之前显而易见,您的代码将会引发ValueError

如何修复它:

def update_letter_view(puzzle, view, index, letter):
    symbol = '^'
    if letter in puzzle and puzzle.index(letter) == index:
        symbol = letter
    return symbol