I have:
a function: def find_str(s, char)
and a string: "Happy Birthday",
I essentially want to input "py" and return 3 but I keep getting 2 to return instead.
Code:
def find_str(s, char):
index = 0
if char in s:
char = char[0]
for ch in s:
if ch in s:
index += 1
if ch == char:
return index
else:
return -1
print(find_str("Happy birthday", "py"))
Not sure what's wrong!
解决方案
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