简体   繁体   中英

How to get index position from a string in python without repetitive results

While in a for-loop of a string , I want to get the index position of that specific letter in that string , but if there are the same letters in that word, it doesn't work.

I looped through the letters in the string and got the index position of the letter (by using .find() or .index() ) for a string consisting of unique letters, but if the string contains the same letters, the index will only be the position of the first letter that appears in the 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]

The 5 and 1 index positions have the same letters ("r"), so the .find() and .index() methods just add the 1 instead of the 5 because it is the first "r" in the string . I was wondering if there is any way to get the specified letter's position in the word. Please help. Thanks!

Find accepts two optional arguments: start (defaults to 0) and end (defaults to end of the string - that fits in your case). Use enumerate to include starting point:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM