字符串中第二个重复字符的索引

raj*_*hon 1 python string

我在python中尝试一个hangman代码.为了匹配单词的字符,iam使用索引函数来获取字符的位置.例如:word ='计算机'

user_input = raw_input('Enter a character :') # say 'T; is given here

if user_input in word:
                print "\nThe Character %c is present in the word \n" %user_input 
                word_dict[word.index(user_input)] = user_input

#so the output will looks like

{0: '_', 1: '_', 2: '_', 3: '_', 4: '_', 5: 'T', 6: '_', 7: '_'} 
Run Code Online (Sandbox Code Playgroud)

现在,我的问题来自于重复的角色.

# Another example 
>>> 'CARTOON'.index('O')
4
Run Code Online (Sandbox Code Playgroud)

对于第二个'O',如何获得其索引.因为我使用了这个'索引'逻辑,所以我希望继续这样做.

the*_*eye 5

根据str.index文档,签名看起来像这样

str.index(sub[, start[, end]])
Run Code Online (Sandbox Code Playgroud)

第二个参数是要搜索的起始索引.因此,您可以传递第一个项目+ 1的索引,以获取下一个索引.

i = 'CARTOON'.index('O')
print 'CARTOON'.index('O', i + 1)
Run Code Online (Sandbox Code Playgroud)

产量

5
Run Code Online (Sandbox Code Playgroud)

上面的代码可以这样写

data = 'CARTOON'
print data.index('O', data.index('O') + 1)
Run Code Online (Sandbox Code Playgroud)

您甚至可以将其作为实用功能,就像这样

def get_second_index(input_string, sub_string):
    return input_string.index(sub_string, input_string.index(sub_string) + 1)

print get_second_index("CARTOON", "O")
Run Code Online (Sandbox Code Playgroud)

注意:如果找不到字符串至少两次,则会抛出ValueError.

更普遍的方式,

def get_index(input_string, sub_string, ordinal):
    current = -1
    for i in range(ordinal):
        current = input_string.index(sub_string, current + 1)
    else:
        raise ValueError("ordinal {} - is invalid".format(ordinal))
    return current

print get_index("AAABBBCCCC", "C", 4)
Run Code Online (Sandbox Code Playgroud)