s.index(x[, i[, j]])
index of the first occurrence of x in s (at or after index i and before index j)
Can you please explain how the above statement is getting executed step by step.
s.index(x[, i[, j]])
index of the first occurrence of x in s (at or after index i and before index j)
Can you please explain how the above statement is getting executed step by step.
hey @Akshay986 ,
its just a simple to return the index value of first occurrence of a string x in string s.
and If you have provided the values for i and j ,
then it first find a substring between those given i and j values , and then search the index of x in that substring.
for exmaple
s = “qwertyqwertyi”
so
if we find s.index(“w”) , we get its first occurrence at index 1
if we find s.index(“w”,2) , we get its first occurrence at index 7 , here as j is not provided then it uses j value as len(s).
if we find s.index(“w”,2,5) , as you see there is no such occurrence of w in this substring, hence it raises a ValueError : Substring Not found.
I hope this would have helped you understand the concept behind s.index() function.
Thank You and Happy Learning
/
thanks for explaining…
i got confused with the syntax i.e. the inner square brackets for i,j respectively. So we can just simply provide start and end index seperated by comma.
Yes, absolutely.
Those square brackets just say, that these parameters are choices provided with default values, so it depend on us do we need to provide custom values to them or not.
When you use string_object.index(substring), it looks for the occurrence of substring in the string_object. If substring is present, the method returns the index at which the substring is present, otherwise, it throws ValueError: substring not found.
Using Python’s “in” operator
The simplest and fastest way to check whether a string contains a substring or not in Python is the “in” operator . This operator returns true if the string contains the characters, otherwise, it returns false .
str="Hello, World!"
print("World" in str)//output is True
Python “in” operator takes two arguments, one on the left and one on the right, and returns True if the left argument string is contained within the right argument string. It is important to note that the “in” operator is case sensitive i.e, it will treat the Uppercase characters and Lowercase characters differently.