To find the index of first occurrence of a substring in a string you can use String. indexOf() function. A string, say str2 , can occur in another string, say str1 , n number of times. There could be a requirement in your Java application, that you have to find the position of the first occurrence of str2 in str1 .
The in operator is the easiest and pythonic way to check if a python string contains a substring. The in and not in are membership operators, they take in two arguments and evaluate if one is a member of the other. They return a boolean value.
The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.
The strchr() function finds the first occurrence of a character in a string. The character c can be the null character (\0); the ending null character of string is included in the search. The strchr() function operates on null-ended strings.
find()
>>> s = "the dude is a cool dude"
>>> s.find('dude')
4
index
and find
Next to the find
method there is as well index
. find
and index
both yield the same result: returning the position of the first occurrence, but if nothing is found index
will raise a ValueError
whereas find
returns -1
. Speedwise, both have the same benchmark results.
s.find(t) #returns: -1, or index where t starts in s
s.index(t) #returns: Same as find, but raises ValueError if t is not in s
rfind
and rindex
:In general, find and index return the smallest index where the passed-in string starts, and
rfind
andrindex
return the largest index where it starts Most of the string searching algorithms search from left to right, so functions starting withr
indicate that the search happens from right to left.
So in case that the likelihood of the element you are searching is close to the end than to the start of the list, rfind
or rindex
would be faster.
s.rfind(t) #returns: Same as find, but searched right to left
s.rindex(t) #returns: Same as index, but searches right to left
Source: Python: Visual QuickStart Guide, Toby Donaldson
to implement this in algorithmic way, by not using any python inbuilt function . This can be implemented as
def find_pos(string,word):
for i in range(len(string) - len(word)+1):
if string[i:i+len(word)] == word:
return i
return 'Not Found'
string = "the dude is a cool dude"
word = 'dude1'
print(find_pos(string,word))
# output 4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With