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.3 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....
Discussions

python - How to raise a ValueError? - Stack Overflow
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 someth... More on stackoverflow.com
🌐 stackoverflow.com
Explain Python ValueError Exception Handling (With Real Examples & Best Practices)
Learn what Python ValueError means, why it occurs, and how to fix it with practical examples, best practices, and real-world use cases. More on accuweb.cloud
🌐 accuweb.cloud
1
January 15, 2024
Python Value Error
Hello everyone, I hope this message finds you well. I was hoping if someone could assist me on this error I have encountered when attempting to clean data. The error seems to advise that the length of values (1000) does not match the length of index (250). Would anyone please kindly suggest ... More on discuss.python.org
🌐 discuss.python.org
5
0
January 24, 2024
Python: difference between ValueError and Exception? - Stack Overflow
I am trying to understand what is a difference between raising a ValueError and an Exception. I have tried both in the same code (even in the same branch) and the result was the same - I got an error More on stackoverflow.com
🌐 stackoverflow.com
🌐
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.
🌐
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.
🌐
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.
🌐
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.
Find elsewhere
🌐
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.
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
🌐
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.
🌐
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.
🌐
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.
🌐
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
🌐
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.
🌐
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....
🌐
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.
🌐
Inngest
inngest.com › blog › python-errors-as-values
Python errors as values: Comparing useful patterns from Go and Rust - Inngest Blog
November 8, 2023 - Demonstrate how to handle errors as values in Python (a traditionally thrown-error language).