How to raise a ValueError?


Question

I have this code which finds the largest index of a specific character in a string, however I would like it to raise a ValueError when the specified character does not occur in a string.

So something like this:

contains('bababa', 'k')

would result in a:

ValueError: could not find k in bababa

How can I do this?

Here's the current code for my function:

def contains(string,char):
  list = []

  for i in range(0,len(string)):
      if string[i] == char:
           list = list + [i]

  return list[-1]
1
95
3/7/2017 5:32:36 PM

raise ValueError('could not find %c in %s' % (ch,str))

158
12/8/2010 11:10:39 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon