0

I'm trying to understand why I'm having the same index again when I apply .index or .find why I'm getting the same index '2' again why not '3'? when a letter is repeated, and what is the alternative way to get an index 3 for the second 'l'

text = 'Hello'
for i in text:
    print(text.index(i))

the output is:

0
1
2
2
4
2
  • 3
    Because index always returns the index of the first occurrence Commented Nov 2, 2020 at 20:02
  • 2
    for the second part of your question - look at enumerate() function to get all index of each and every char in the string. eg. for idx, ch in enumerate(text): Commented Nov 2, 2020 at 20:09

3 Answers 3

4

It's because .index() returns the lowest or first index of the substring within the string. Since the first occurrence of l in hello is at index 2, you'll always get 2 for "hello".index("l").

So when you're iterating through the characters of hello, you get 2 twice and never 3 (for the second l). Expanded into separate lines, it looks like this:

"hello".index("h")   # = 0
"hello".index("e")   # = 1
"hello".index("l")   # = 2
"hello".index("l")   # = 2
"hello".index("o")   # = 4

Edit: Alternative way to get all indices:

One way to print all the indices (although not sure how useful this is since it just prints consecutive numbers) is to remove the character you just read from the string:

removed = 0
string = "hello world"    # original string
for char in string:
  print("{} at index {}".format(char, string.index(char) + removed))  # index is index() + how many chars we've removed
  string = string[1:]    # remove the char we just read
  removed +=1            # increment removed count
Sign up to request clarification or add additional context in comments.

Comments

1
text = 'Hello'
for idx, ch in enumerate(text):
    print(f'char {ch} at index {idx}')  

output

char H at index 0
char e at index 1
char l at index 2
char l at index 3
char o at index 4

Comments

0

If you want to find the second occurance, you should search in the substring after the first occurance

text = 'Hello'
first_index = text.index('l')
print('First index:', first_index)

second_index = text.index('l', first_index+1) # Search in the substring after the first occurance
print('Second index:', second_index)

The output is:

First index: 2
Second index: 3

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.