In this tutorial, we will delve into one of Python’s built-in string methods – find()
. This method is incredibly useful when you need to determine the position of a specific substring within a larger string.
What is the find() Method?
The find()
method in Python is used to locate the position of a substring in a given string. It returns the lowest index where the substring starts. If it doesn’t find the substring, it returns -1.
Syntax
string.find(substring, start, end)
The parameters are:
- substring: The string you want to search for.
- start (optional): Where to start the search. Default is 0.
- end (optional): Where to end the search. Default is end of the string.
A Simple Example
text = "Hello, welcome to my world."
result = text.find("welcome")
print(result) # Output: 7
In this example, our code successfully found ‘welcome’ at index 7 in our text string.
If Substring Not Found
text = "Hello, welcome to my world."
result = text.find("goodbye")
print(result) # Output: -1
This time ‘goodbye’ was not found in our text string so it returned -1 as expected.
Finding with Start and End Parameters
text = "Hello, welcome to my world."
result = text.find("o", 5, 20)
print(result) # Output: 15
Here we’re searching for ‘o’ between index 5 and 20. The first ‘o’ in this range is found at index position 15.
Conclusion
The Python find()
method is a powerful tool for locating the position of substrings within larger strings. Remember that it’s case-sensitive and returns -1 if the substring isn’t found. Happy coding!