Can the "in" operator be used to get the specific index of duplicate characters?


#1

Question

The in operator lets us check if a character is in a string. However, can the in operator be used to get the specific index of duplicate characters?

Answer

The in operator will usually return True at the first instance that a character appears within a string. It also does not have any way of returning the index where a character was found.

In order to get the indexes of a character that appears within a string, any number of times, one method might be to utilize a for loop iterating through each index, and checking each character for a match.

Example

# We first check that a string contains the character.
# If so, we store the indexes in a list.
string = "xylophone"
target = "o"

is_contained = target in string
indexes = []

if is_contained:              
  for index in range(len(string)):
    if string[index] == target:
      indexes.append(index)

print(indexes) # [3, 6]