I got some simple code:
def find(str, ch): for ltr in str: if ltr == ch: return str.index(ltr) find("ooottat", "o")
The function only return the first index. If I change return to print, it will print 0 0 0. Why is this and is there any way to get 0 1 2
?
1. Using indexOf() and lastIndexOf() method. The String class provides an indexOf() method that returns the index of the first appearance of a character in a string. To get the indices of all occurrences of a character in a String, you can repeatedly call the indexOf() method within a loop.
You can use the index() method to find the index of the first element that matches with a given search object. The index() method returns the first occurrence of an element in the list.
Use the string. count() Function to Find All Occurrences of a Substring in a String in Python. The string. count() is an in-built function in Python that returns the quantity or number of occurrences of a substring in a given particular string.
This is because str.index(ch)
will return the index where ch
occurs the first time. Try:
def find(s, ch): return [i for i, ltr in enumerate(s) if ltr == ch]
This will return a list of all indexes you need.
P.S. Hugh's answer shows a generator function (it makes a difference if the list of indexes can get large). This function can also be adjusted by changing []
to ()
.
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