简体   繁体   中英

finding the index of the same letter in a string

Currently working with

def order(word):
  for each in word:
    print str(word.index(each))+ ": "+each

If I run order("Ranger") , the code works as I want to and it gives me:

0: R
1: a
2: n
....and so on until "5: r"

but if I put in any word with repeating letters like "hall" or "silicon," I get the position value of the first iteration of the word such as:

order("Hall")
0: H
1: a
2: l
2: l

How can I get the the function to return the following?

0: H
1: a
2: l
3: l

str.index() just returns the lowest index of the substring.

You can just enumerate a string for your purposes:

def order(word):
    for index, letter in enumerate(word):
        print('{}: {}'.format(index,letter))

Also, please consider using python 3.x.

Since you tagged this as Python here is a Python implementation.

def order(word):
  for i in range(len(word)):
    print(i+1, ":", word[i])
order("hall")

I am basically iterating through the length of the word and am printing out the character at that position. In your case, str.index() prints out the first occurrence of the character. Hope this helped.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM