I was writing a program to find out the index number of a given value of 'o' in a string="Hello World". I have done it using three ways, first is using the index(), second is using the for loop with a counter variable, third is using the for loop with enumerate() function.
I have a problem with the counter variable. Hence, there are two 'o' in "Hello World" first is at the 4th index and the second is at the 7th index. but my counter variable is showing me 4 and 6 as the output. But the enumerate() is showing me 4 and 7 as the output. I want to know what is wrong with my counter variable.
Thanks in advance.
Here is my code
val = 'Hello World'
counter = 0
print("Index of 'o' Using Index Function: ", val.index('o', 5))
print('---------------------------------------')
for i in val:
if i == 'o':
print(i, counter)
#I don't want to use break here because I want to print all the index of 'o'
else:
counter += 1
print("------------------")
for i, var in enumerate(val):
print(i, var)
Here Is the Output
Index of 'o' Using Index Function: 7
---------------------------------------
o 4
o 6
------------------
0 H
1 e
2 l
3 l
4 o
5
6 W
7 o
8 r
9 l
10 d
counterregardless of the match.counter += 1only wheni != "o"i.e., in theelsepart; butcountermust go up whether it hits"o"or not, right?elseblock and let counter stay in the loopval = "ooooooooooo"and run your code and see whatcounterhas.