我正在尝试用 python 编写刽子手代码。为了匹配单词的字符,我使用索引函数来获取字符的位置。 例如: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: '_'}
现在,当重复字符出现时,我的问题就来了。
# Another example
>>> 'CARTOON'.index('O')
4
对于第二个'O',如何获取它的索引。因为我已经使用了这种“索引”逻辑,所以我希望继续这种方式。
请您参考如下方法:
根据 str.index docs , 签名看起来像这样
str.index(sub[, start[, end]])
第二个参数是要搜索的起始索引。因此,您可以传递为第一项获得的索引 + 1,以获取下一个索引。
i = 'CARTOON'.index('O')
print 'CARTOON'.index('O', i + 1)
输出
5
上面的代码可以这样写
data = 'CARTOON'
print data.index('O', data.index('O') + 1)
你甚至可以把它作为一个效用函数,像这样
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")
注意:如果字符串至少两次都没有找到,这将抛出 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)
