0
a = "programming in python is Fun"

a.find("i") = 8

It returns index of first occurrence of "i" in a.
Is it possible to find index of second "i"?

Red
  • 26,798
  • 7
  • 36
  • 58
  • Yes, look into index method's behavior. https://docs.python.org/3/library/stdtypes.html#common-sequence-operations – lllrnr101 Feb 03 '21 at 15:12

3 Answers3

3

find() takes an optional start index as well which you can use as:

a = "programming in python is Fun"
first = a.find('i')
print(a.find('i',first+1))
Krishna Chaurasia
  • 8,924
  • 6
  • 22
  • 35
2

You can use enumerate() with list comprehension to find all the indexes as:

s = "programming in python is Fun"
my_char = "i"

my_indexes = [i for i, x in enumerate(s) if x == my_char]
# where `my_indexes` holds:
#    [8, 12, 22]

Here my_char is the character of which you want to find the index. And my_indexes is a list containing the indexes of each time my_char is found in the string. Please refer enumerate() document for more details.

Hence, you can access index of second occurrence as:

>>> my_indexes[1]
12
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
  • that one is very cool. probably not as fast as ```.find()``` on paper, but the algo is better imho. If I may, remove that ```, x in enumerate```, ```ì for i in s``` will do just fine, a string is just a list of chars. – Loïc Feb 03 '21 at 15:26
1

You can also use numpy in the following way:

import numpy as np
a = "programming in python is Fun"
x = np.frombuffer(a.encode(), dtype=np.uint8)
np.where(x == ord('i')) # (array([ 8, 12, 22]),)

Using np.frombuffer reinterpret str as a char buffer and then using np.where will return all the indices that will match the character you are interested in (or more accurately the integer representing the Unicode character, using ord).

David
  • 8,113
  • 2
  • 17
  • 36
  • isn't loading numpy a bit heavy for that task ? – Loïc Feb 03 '21 at 15:22
  • 1
    @Loïc It might be overkill, but if you have a very long string I guess this will be the fast. Of course, I also wanted to give some other approach to the one given. – David Feb 03 '21 at 15:23