Reputation: 25
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
Upvotes: 0
Views: 262
Reputation: 146
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)
counter += 1
print("------------------")
for i, var in enumerate(val):
print(i, var)
Upvotes: 0
Reputation: 1919
I suggest you using this code i have written
def count(string, letter):
assert letter in string, f"The letter {letter!r} is not in the string {string!r}"
return [i for i, j in enumerate(string) if j == letter]
print(count('Hello World', "o"))
Which it prints out [4, 7]
as you want.
it is called list-comprehension, it goes character by character and if the character equals to letter
, then it adds it to the list.
equals to:
counter = []
for i, j in enumerate(string):
if j == letter:
counter.append(i)
Upvotes: -1
Reputation: 50
Seems like error in the counting logic. first 'o' is not counted as counter increment was placed on else block. Try this,
for i in val:
if i == 'o':
print(i, counter)
counter += 1
print("------------------")
Upvotes: 2
Reputation: 53
You need to update the counter variable even when o
is found.
if i == 'o':
print(i, counter)
counter += 1
Upvotes: 3