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

122
August 06, 2019, at 08:50 AM

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!

Answer 1

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)
Rent Charter Buses Company
READ ALSO
How to fix unsafe implementation of HostnameVerifier

How to fix unsafe implementation of HostnameVerifier

I have received this warning from Playstore because my code bellow is accepting all hosts

154
cannot call finish(); , but i can call system.exit [0]i am

cannot call finish(); , but i can call system.exit [0]i am

any body know why i cannot cast finish (); on the attached codes ? also i cannot cast any intent inside of it

124
What is MIDlet?

What is MIDlet?

I just saw a code

144
Check if an arrayList of points are inside a defined list of points

Check if an arrayList of points are inside a defined list of points

I'm trying to check if an ArrayList of points (represented as two Float) are inside another defined list of pointsI decided to check them on at time, and I compared them with the first pair of points of the other polygon and the pair at his half

152