What is the string.find method in Python?
The find method in Python returns the index of the first occurrence of a substring in a string. If the substring is not present in the string, then -1 will be returned.
Syntax
string.find(substring [, start[, end]] )
Arguments
-
substring: String to be searched. -
start: The index from which the substring search should start. This is an optional value, and by default the value is0. -
end: The index to which the substring search should happen. This is an optional value, and by default the value is the length of the string.
Return value
This is the first index at which the substring is found. If the substring is not present, -1 is returned.
Example
string = "JavaScript";print("The index of Java in JavaScript is")print(string.find("Java"));print("\nThe index of Script in JavaScript is")print(string.find("Script"));print("\nThe searching for 'pt' in JavaScript from index 8")print(string.find("pt", 8));print("\nThe searching for 'va' in JavaScript from index 1 and 5")print(string.find("va", 1,5));print("\nThe searching for 'Python' in JavaScript")print(string.find("Python"));
In the code above, we create a JavaScript string:
string.find("Java")
- We use the
findmethod to check the index at whichJavais present in theJavaScriptstring. We will get0as a result.
string.find("Script")
- We use the
findmethod to check the index at whichScriptis present in the stringJavaScript. We will get4as a result.
string.find("pt", 8)
- We use the
findmethod to check the index at whichptis present in theJavaScriptstring from the8thindex. We will get8as a result.
string.find("va", 1,5)
- We use the
findmethod to check the index at whichvais present in the stringJavaScriptbetween the 1 to 5 index. We will get2as a result.
print(string.find("Python"));
- We use the
findmethod to check the index at whichPythonis present. We will get-1becausePythonis not present in theJavaScriptstring.