How to raise a ValueError?

I have this code that 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 the string.

So something like this:

 contains('bababa', 'k') 

will result in:

ValueError: could not find k in bababa

How can i do this?

Here is 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] 
+90
python string
Dec 08 '10 at 23:08
source share
5 answers

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

+147
Dec 08 '10 at 23:10
source share

Here is a revised version of your code that still works, plus it illustrates how to raise a ValueError way you want. By the way, I think find_last() , find_last_index() , or something similar, would be a more descriptive name for this function. Adding to the possible confusion is due to the fact that Python already has a container object method called __contains__() that does something a little different in __contains__() membership testing.

 def contains(char_string, char): largest_index = -1 for i, ch in enumerate(char_string): if ch == char: largest_index = i if largest_index > -1: # any found? return largest_index # return index of last one else: raise ValueError('could not find {!r} in {!r}'.format(char, char_string)) print(contains('mississippi', 's')) # -> 6 print(contains('bababa', 'k')) # -> 
 Traceback (most recent call last): File "how-to-raise-a-valueerror.py", line 15, in <module> print(contains('bababa', 'k')) File "how-to-raise-a-valueerror.py", line 12, in contains raise ValueError('could not find {} in {}'.format(char, char_string)) ValueError: could not find 'k' in 'bababa' 

Updating is a significantly easier way

Blimey! Here's a much shorter version — essentially a one-line version — which is also probably faster because it flips (via [::-1] ) the string before doing a direct search for the first matching character in it and does this using the quick built-in index() method index() . As for your actual question, the nice little bonus convenience that comes with using index() is that it already raises a ValueError when a character substring is not found, so no extra action is required for this.

This is a quick unit test:

 def contains(char_string, char): # Ending - 1 adjusts returned index to account for searching in reverse. return len(char_string) - char_string[::-1].index(char) - 1 print(contains('mississippi', 's')) # -> 6 print(contains('bababa', 'k')) # -> 
 Traceback (most recent call last): File "better-way-to-raise-a-valueerror.py", line 9, in <module> print(contains('bababa', 'k')) File "better-way-to-raise-a-valueerror", line 6, in contains return len(char_string) - char_string[::-1].index(char) - 1 ValueError: substring not found 
+23
Dec 09 '10 at 0:15
source share
 >>> def contains(string, char): ... for i in xrange(len(string) - 1, -1, -1): ... if string[i] == char: ... return i ... raise ValueError("could not find %r in %r" % (char, string)) ... >>> contains('bababa', 'k') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 5, in contains ValueError: could not find 'k' in 'bababa' >>> contains('bababa', 'a') 5 >>> contains('bababa', 'b') 4 >>> contains('xbababa', 'x') 0 >>> 
+10
Dec 08 '10 at 23:35
source share

In latest python version you can use fstrings to do this

allows value = "Hello"

 raise ValidationError(f"{value} is not valid category") 
+6
Nov 02 '17 at 11:55
source share
 >>> response='bababa' ... if "K" in response.text: ... raise ValueError("Not found") 
+4
Mar 03 '17 at 10:19
source share



All Articles