如何在Python中重写index()函数,使字符串未找到时仅返回-1且不抛出异常
str.index() Return -1 Instead of Throwing an Error Got it, let's tackle this problem. The built-in Python str.index() method throws a ValueError when it can't find the specified substring, but you want it to quietly return -1 instead. Here are a few practical approaches to achieve this:
1. Create a Safe Wrapper Function (Recommended)
The simplest and safest way is to write a helper function that wraps the original index() method and handles the exception:
def safe_string_index(s: str, sub: str, start: int = 0, end: int | None = None) -> int: try: # Delegate to the original index method return s.index(sub, start, end) except ValueError: # Return -1 when the substring isn't found return -1
How to Use It:
a = 'abc' print(safe_string_index(a, 'q')) # Output: -1 print(safe_string_index(a, 'b')) # Output: 1
This approach keeps the original str.index() behavior intact for other code, so you don't risk breaking anything else.
2. Subclass str for Custom Behavior
If you want all instances of your custom string type to have this behavior, create a subclass of str and override the index() method:
class SafeStr(str): def index(self, sub: str, start: int = 0, end: int | None = None) -> int: try: # Call the parent class's index method return super().index(sub, start, end) except ValueError: return -1
How to Use It:
a = SafeStr('abc') print(a.index('q')) # Output: -1 print(a.index('a')) # Output: 0
This is great if you're working with a codebase where you can use your custom string type consistently.
3. Monkey-Patch the Built-in str Class (Use with Caution)
If you absolutely need every existing str instance to have this modified behavior, you can monkey-patch the str.index() method. Warning: This changes the behavior for all code running in your Python session, which might break libraries or other parts of your code that rely on the original exception-throwing behavior.
# Save a reference to the original index method original_str_index = str.index def patched_index(self, sub: str, start: int = 0, end: int | None = None) -> int: try: return original_str_index(self, sub, start, end) except ValueError: return -1 # Replace the built-in method str.index = patched_index
How to Use It:
a = 'abc' print(a.index('q')) # Output: -1 print(a.index('c')) # Output: 2
Only use this if you're certain there won't be unintended side effects!
内容的提问来源于stack exchange,提问作者nimop

