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