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!
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.
Use the find() Function to Find First Occurrence in Python We can use the find() function in Python to find the first occurrence of a substring inside a string. The find() function takes the substring as an input parameter and returns the first starting index of the substring inside the main string.
Python String find() method returns the lowest index or first occurrence of the substring if it is found in a given string. If it is not found then it returns -1. Parameters: sub: It is the substring that needs to be searched in the given string.
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.
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