在字符串中查找相同字母的索引

0 python jython

目前与

def order(word):
  for each in word:
    print str(word.index(each))+ ": "+each
Run Code Online (Sandbox Code Playgroud)

如果我运行order("Ranger"),代码会按照我的意愿工作,它给了我:

0: R
1: a
2: n
....and so on until "5: r"
Run Code Online (Sandbox Code Playgroud)

但是如果我输入任何带有重复字母的单词,例如“hall”或“silicon”,我会得到该单词第一次迭代的位置值,例如:

0: R
1: a
2: n
....and so on until "5: r"
Run Code Online (Sandbox Code Playgroud)

我怎样才能让函数返回以下内容?

order("Hall")
0: H
1: a
2: l
2: l
Run Code Online (Sandbox Code Playgroud)

小智 5

str.index() 只返回子字符串的最低索引。

您可以只使用enumerate一个字符串来满足您的目的:

def order(word):
    for index, letter in enumerate(word):
        print('{}: {}'.format(index,letter))
Run Code Online (Sandbox Code Playgroud)

另外,请考虑使用 python 3.x。