To find the index of a substring in Python, you can use the find
method of the String class.
In this example,
str
with a string value.find
method of str
to find the index of a specific substring within str
.find
method returns the starting index of the substring in the string.str = "Hello World"
index = str.find("World")
print("Index of substring is:", index)
Index of substring is: 6
In this example,
str1
and str2
with different values.find
method of str1
to find the index of str2
within str1
.find
method returns the starting index of str2
in str1
.str1 = "apple banana cherry banana"
str2 = "cherry"
index = str1.find(str2)
print("Index of substring is:", index)
Index of substring is: 13
In this tutorial, we learned How to find the Index of Substring in Python language with well detailed examples.