首页 > 解决方案 > 如何在没有重复结果的情况下从python中的字符串获取索引位置

问题描述

在 a 的 for 循环中string,我想获取该index特定字母在 that 中的位置string,但如果该单词中有相同的字母,则它不起作用。

我遍历了 中的字母,string并获得了字母的index位置(通过使用.find()or .index())以获取string由唯一字母组成的 a ,但如果string包含相同的字母,则索引将只是出现在 中的第一个字母的位置string

indexList = [] #list of stored indexes
word = "grocery" #could be any string, just using "grocery" as an example
for letter in word:
  index = word.find(letter)
  indexList.append(index)

print (indexList)

#Expected output: [0, 1, 2, 3, 4, 5, 6]
#Actual output: [0, 1, 2, 3, 4, 1, 6]

5 和 1index位置具有相同的字母(“r”),因此.find()and.index()方法只是添加 1 而不是 5,因为它是string. 我想知道是否有任何方法可以获取指定字母在单词中的位置。请帮忙。谢谢!

标签: pythonpython-3.xstringfor-loopindexing

解决方案


Find接受两个可选参数:(start默认为 0)和end(默认为字符串结尾 - 适合您的情况)。使用 enumerate 包括起点:

for i, letter in enumerate(word):
    index = word.find(letter, i)
    indexList.append(index)

推荐阅读