我正在尝试用 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’,如何获取它的索引。因为我已经使用了这种“索引”逻辑,所以我希望继续这样做。
原文由 rajpython 发布,翻译遵循 CC BY-SA 4.0 许可协议
根据
str.index
文档,签名看起来像这样第二个参数是要搜索的起始索引。因此,您可以传递为第一项获得的索引 + 1,以获取下一个索引。
输出
上面的代码可以这样写
你甚至可以把它作为一个效用函数,像这样
注意: 如果至少两次找不到该字符串,则会抛出
ValueError
。更普遍的方式,