YouTip LogoYouTip

Att String Index

## Python String index() Method In Python, the `index()` method is a built-in string method used to search for the first occurrence of a specified substring within a string. It works similarly to the `find()` method, but with one critical difference: if the substring is not found, `index()` raises a `ValueError` exception, whereas `find()` returns `-1`. --- ## Syntax ```python str.index(substring, beg=0, end=len(string)) ``` ### Parameters * **`substring`**: The target substring you want to search for. * **`beg`** *(Optional)*: The starting index of the search range. The default value is `0` (the beginning of the string). * **`end`** *(Optional)*: The ending index of the search range. The default value is the length of the string. ### Return Value * Returns the **lowest index** (0-based) where the substring starts if it is found within the specified range. * Raises a **`ValueError: substring not found`** exception if the substring does not exist in the string. --- ## Code Examples ### Basic Usage and Slicing The following example demonstrates how to use the `index()` method to find substrings, search within a specific range, and handle the exception when a substring is not found. ```python #!/usr/bin/python3 # Define the source string and the substring to search for str1 = "this is string example....wow!!!" str2 = "exam" # Example 1: Search the entire string print(str1.index(str2)) # Output: 15 # Example 2: Search starting from index 10 print(str1.index(str2, 10)) # Output: 15 # Example 3: Search starting from index 40 (out of bounds / substring not present in this range) try: print(str1.index(str2, 40)) except ValueError as e: print(f"Error: {e}") ``` ### Output ```text 15 15 Error: substring not found ``` --- ## Key Considerations ### 1. `index()` vs. `find()` * Use **`find()`** if you expect that the substring might not be present and you want to handle it with a simple conditional check (e.g., `if index == -1:`). * Use **`index()`** if the substring *must* be present, or if you prefer using `try-except` blocks to handle missing substrings as exceptional cases. ### 2. Exception Handling Because `index()` raises a `ValueError` when the substring is missing, it is best practice to wrap your code in a `try-except` block to prevent your program from crashing: ```python text = "Learn Python programming" try: position = text.index("Java") except ValueError: print("The substring was not found in the text.") ```
← Att String IslowerPython Exceptions β†’