Search in line
To search within a string in Python, use the find()
method.
It has three forms and returns the index of the 1st occurrence of the substring in the string:
1) find(str)
- substring str
is searched from the beginning of the string to its end;
2) find(str, start)
- using the start
parameter, the starting index is set, and it is from it that the search is performed;
3) find(str, start, end) -
using the end
parameter, the end index is set, the search is performed before it.
When the substring is not found, the method returns -1:
welcome = "Hello world! Goodbye world!"
index = welcome.find("wor")
print(index) #6
# look for from 10th to 15th index
index = welcome.find("wor", 10, 15)
print(index) # -1
You can search from the end of the string. For this, the rfind()
method (from the English reverse find) is used - it returns the index of the last occurrence of a substring in a string.
Note: data methods do not look for the number of occurrences, but only determine whether there is such a substring in the string or not.