top of page

Python (4): Find Occurance




Is there a construct in Python similar to indexOf() in JavaScript? The answer is YES. According to my previous article, indexOf() in JavaScript is used for finding the first occurance of the value in the parenthesis() in a string or array. But today we'are not going to talk about indexOf(), but it's alternative in Python: if ... in ... + index()



Let's dive into an example.



if b in a:
    return a.index(b)
else:
    return -1


Let's say both a and b are strings, which a = "flower", b = "flow" (My favourite example).


if b in a means if b is a substring of a, then return a.index(b).


In other words, it just simply means "Is b found in a?".


index() is similar to indexOf() in JavaScript, which returns the index number of the first occurrence of the value in the parenthesis().


If b is find in the first character of a, then it'll return 0.


Similarly, if b is find in the second character of a, then it'll return 1, then 2, 3, 4... and so on.


However, index() will not return -1 if b is not found in a, but returning a error.


So, in this example, the return value is 0 because b is found in the first character of a, which "flow" is found at the beginning of "flower".








Congratulations on successfully completing the tutorial!


You've acquired valuable knowledge.


See you in Python (5)!








© 2023 Harmony Pang. All rights reserved.








Comments


bottom of page