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"
?
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"
?
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))
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
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
).