Python: Find a substring in a string and returning the index of the substring
Adding onto @demented hedgehog answer on using find()
In terms of efficiency
It may be worth first checking to see if s1 is in s2 before calling find()
.
This can be more efficient if you know that most of the times s1 won't be a substring of s2
Since the in
operator is very efficient
s1 in s2
It can be more efficient to convert:
index = s2.find(s1)
to
index = -1
if s1 in s2:
index = s2.find(s1)
This is useful for when find()
is going to be returning -1 a lot.
I found it substantially faster since find()
was being called many times in my algorithm, so I thought it was worth mentioning
There's a builtin method find on string objects.
s = "Happy Birthday"
s2 = "py"
print(s.find(s2))
Python is a "batteries included language" there's code written to do most of what you want already (whatever you want).. unless this is homework :)
find
returns -1 if the string cannot be found.
There is one other option in regular expression, the search
method
import re
string = 'Happy Birthday'
pattern = 'py'
print(re.search(pattern, string).span()) ## this prints starting and end indices
print(re.search(pattern, string).span()[0]) ## this does what you wanted
By the way, if you would like to find all the occurrence of a pattern, instead of just the first one, you can use finditer
method
import re
string = 'i think that that that that student wrote there is not that right'
pattern = 'that'
print([match.start() for match in re.finditer(pattern, string)])
which will print all the starting positions of the matches.
Ideally you would use str.find or str.index like demented hedgehog said. But you said you can't ...
Your problem is your code searches only for the first character of your search string which(the first one) is at index 2.
You are basically saying if char[0]
is in s
, increment index
until ch == char[0]
which returned 3 when I tested it but it was still wrong. Here's a way to do it.
def find_str(s, char):
index = 0
if char in s:
c = char[0]
for ch in s:
if ch == c:
if s[index:index+len(char)] == char:
return index
index += 1
return -1
print(find_str("Happy birthday", "py"))
print(find_str("Happy birthday", "rth"))
print(find_str("Happy birthday", "rh"))
It produced the following output:
3
8
-1