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

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]
4 Likes

does count() work in this?

str.count() returns the number of instances of a substring within a string, but not their indices.

1 Like

This is the code for the second question in this exercise. What are the deficiencies?

def common_letters(string_one, string_two):
  str3 = []
  for i in string_one:
    if i in string_two and i not in str3:
      str3.append(i)
  return str3
new_word = print(common_letters("acsac", "bfec"))
2 Likes

It’s inefficient to search through str2 and str3 every letter. Use sets. Better yet, use Counter or set and nothing else.

>>> Counter('acsac') & Counter('bfec')
Counter({'c': 1})
>>> Counter('acsac') & Counter('bfecc')
Counter({'c': 2})
>>> set('acsac') & set('bfecc')
{'c'}
2 Likes

In the if statement, I believe you placed the ‘not’ statement incorrectly. The ‘not’ should go before the statement that it should negate, not halfway as you put it.
I think it should be:

if i in string_two and not i in str3:

It’s a subtle difference, but should do the trick.

1 Like

Just a reminder:

If the exercise ask for a LIST of commons letters between strings, use SET (syntax: set(string_name) & set(string_name2)), this will give you a dictionary of commons letters. After that, use a for loop through the dictionary and add each element in a empty list assigned before.

emptyList = []

for eachElement in listBySet:
    emptyList.adding (eachElement)