Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find char in string and get all the indexes?

Tags:

python

string

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?

like image 805
William Xing Avatar asked Jun 20 '12 14:06

William Xing


People also ask

How do you get all indexes of a char in a string?

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.

How do you find the index of a character in a list?

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.

How do you find all occurrences in a string?

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.


1 Answers

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 ().

like image 134
Lev Levitsky Avatar answered Oct 05 '22 22:10

Lev Levitsky