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

Answer from NPE on Stack Overflow
🌐
Python
docs.python.org › 3 › library › exceptions.html
Built-in Exceptions — Python 3.14.4 documentation
Passing arguments of the wrong type (e.g. passing a list when an int is expected) should result in a TypeError, but passing arguments with the wrong value (e.g. a number outside expected boundaries) should result in a ValueError.
🌐
W3Schools
w3schools.com › python › ref_exception_valueerror.asp
Python ValueError Exception
Python Examples Python Compiler ... Python Certificate Python Training ... The ValueError exception occurs if a function receives a value of wrong type....
🌐
Turing
turing.com › kb › valueerror-in-python-and-how-to-fix
What is ValueError in Python & How to fix it
When a user calls a function with an invalid value but a valid argument, Python raises ValueError. Even though the value is the correct argument, it typically happens in mathematical processes that call for a specific kind of value. When an object is given the incorrect value, the Python ValueError is raised.
🌐
Real Python
realpython.com › ref › builtin-exceptions › valueerror
ValueError | Python’s Built-in Exceptions – Real Python
Occurs when a function or operation receives an argument that has the right type but an inappropriate value.
🌐
Carleton University
cs.carleton.edu › cs_comps › 1213 › pylearn › final_results › encyclopedia › valueError.html
Error Encyclopedia | Value Error
In Python, a value is the information that is stored within a certain object. To encounter a ValueError in Python means that is a problem with the content of the object you tried to assign the value to.
🌐
Educative
educative.io › answers › what-is-valueerror-in-python
What is ValueError in Python?
ValueError in Python is raised when a user gives an invalid value to a function but is of a valid argument.
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-valueerror-exception-handling-examples
Python ValueError Exception Handling: Examples & Fixes | DigitalOcean
August 3, 2022 - Python ValueError is raised when a function receives an argument of the correct type but an inappropriate value.
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-fix-valueerror-exceptions-in-python
How To Fix Valueerror Exceptions In Python - GeeksforGeeks
July 23, 2025 - In conclusion, resolving ValueError exceptions in Python involves meticulous examination of input data and ensuring compatibility with the expected format. Employing proper validation techniques, such as try-except blocks and conditional statements, can help preemptively catch and handle potential issues.
Find elsewhere
🌐
Rollbar
rollbar.com › home › how to fix valueerror exceptions in python
How to Fix ValueError Exceptions in Python | Rollbar
June 24, 2024 - The Python ValueError is an exception that occurs when a function receives an argument of the correct data type but an inappropriate value.
Top answer
1 of 4
190

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

2 of 4
30

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

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'

Update — A substantially simpler way

Wow! Here's a much more concise version—essentially a one-liner—that is also likely faster because it reverses (via [::-1]) the string before doing a forward search through it for the first matching character and it does so using the fast built-in string index() method. With respect to your actual question, a nice little bonus convenience that comes with using index() is that it already raises a ValueError when the character substring isn't found, so nothing additional is required to make that happen.

Here it is along with 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
🌐
iO Flood
ioflood.com › blog › python-valueerror
[SOLVED] Python ValueError | Causes and Solutions
January 30, 2024 - Think of a ValueError as a traffic signal in your code – it stops the flow of your program when it encounters an inappropriate value. It’s a mechanism Python uses to ensure that the functions and operations in your code are receiving the right kind of values they expect.
🌐
Accuweb
accuweb.cloud › home › explain python valueerror exception handling (with real examples & best practices)
Explain Python ValueError Exception Handling (With Real Examples & Best Practices)
January 15, 2024 - Python ValueError is raised when a function receives a value of the correct type but an inappropriate or invalid value.
🌐
Initial Commit
initialcommit.com › blog › valueerror-python
Python ValueError Exception – How to Identify & Handle
January 9, 2023 - ... exception ValueError: Raised when an operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.
🌐
LabEx
labex.io › tutorials › python-how-to-manage-valueerror-in-python-417443
How to manage ValueError in Python | LabEx
Python is a powerful and versatile programming language, but like any language, it comes with its own set of challenges. One such challenge is the ValueError exception, which can occur when a function receives an argument of the correct type but an inappropriate value.
🌐
Python documentation
docs.python.org › 3 › tutorial › errors.html
8. Errors and Exceptions — Python 3.14.3 documentation
import sys try: f = open('myfile.txt') s = f.readline() i = int(s.strip()) except OSError as err: print("OS error:", err) except ValueError: print("Could not convert data to an integer.") except Exception as err: print(f"Unexpected {err=}, {type(err)=}") raise
🌐
EDUCBA
educba.com › home › software development › software development tutorials › python tutorial › python valueerror
Python ValueError | How to Avoid ValueError in Python with Examples
May 13, 2024 - In Python, the worth is data that is put away inside a specific item. To experience a ValueError in Python implies that is an issue with the substance of the article you attempted to allocate the incentive to. This is not to be mistaken for types in Python. Hence, Python ValueError is raised when capacity gets a contention of the right kind; however, it an unseemly worth it.
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
AskPython
askpython.com › home › handling valueerror in python: detecting strings and integers
Handling ValueError in Python: Detecting Strings and Integers - AskPython
April 29, 2023 - Most exceptions in Python are not ... strings and integers using exception handling. ValueError occurs when a function receives an argument of the wrong type....
🌐
Scaler
scaler.com › home › topics › python valueerror
Python ValueError - Scaler Topics
December 15, 2022 - As discussed above, Value Error in python occurs when a correct argument type but an incorrect value is supplied to a function. There are many reasons you might see the Python ValueError pop-ups and these are mentioned below:
🌐
DataCamp
datacamp.com › tutorial › exception-handling-python
Exception & Error Handling in Python | Tutorial by DataCamp | DataCamp
December 12, 2024 - ValueError: occurs when the operation or function receives an argument with the right type but the wrong value. ZeroDivisionError: raised when you divide a value or variable with zero. SyntaxError: raised by the parser when the Python syntax is wrong.
Top answer
1 of 2
8
@Liam Hayes (https://teamtreehouse.com/liamhayes) Hi! I have a note about @Steven Parker (https://teamtreehouse.com/stevenparker)'s example (especially the second one). When I was trying to wrap my head around this, I could not for the life of me understand why the built-in function for changing something to an int would give a ValueError with a string as opposed to a TypeError. Surely, it's expecting a number, right? Well, no. It isn't. The int() function takes either a number or a string. It can convert the string "21" to the integer 21, but it can't convert "dog" to a number. Thus, it's getting the right type, but it's still not a value that it can convert. This is when we get the ValueError. It's of the right type, but the value is such that it still can't be done. That being said, if we tried to send in something that was neither a string nor a number, it would have generated a TypeError as it is of the wrong type. Hope this helps! :sparkles: edited for additional note In your own custom made functions, you can pass in whatever you want, although ideally, you know what you're passing in. This is not true of built-in functions in Python. When in doubt, check the documentation for the function in question.
2 of 2
0
A TypeError occurs when an operation or function is applied to an object of inappropriate type. A ValueError occurs when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError. Examples: passing arguments of the wrong type (e.g. passing a list when an int is expected) should result in a TypeError, but passing arguments with the wrong value (e.g. a number outside expected boundaries) should result in a ValueError. For more details, see the Exceptions page (https://docs.python.org/3/library/exceptions.html) of the Python documentation.