Reputation: 1
I tried to print the index of every i
in the word Mississippi
. I've got the result but the print statement is repeating 3 times. This is the code
s="Mississippi"
start=0
while start<len(s):
print "the index of i is: ", s.find('i',start,len(s))
start=start+1
Upvotes: 0
Views: 9028
Reputation: 3
import re
s="Wisconsin"
for c in re.finditer('i',s):
print c.start(0)
Upvotes: 0
Reputation: 51
do you want to print the indexes as a list? try this:
l = []
for index, char in enumerate('mississippi'):
if char == 'i':
l.append(index)
print "the index of i is: ", l
the result will be:
the index of i is: [1, 4, 7, 10]
Upvotes: 1
Reputation: 1
Because of the while loop, you print the last found position of "i" in each run.
I would prefer a for loop over the string:
s="Misssssissippi"
start=0
character="i"
for i in s:
if (i == character):
print "the index of i is: ", start
start=start+1
Upvotes: 0
Reputation: 768
If you use enumerate then you iterate through the string, looking at each letter and idx
is counting upwards as you go.
for idx, letter in enumerate(s):
if letter == "i":
print "the index of i is: ", idx
Upvotes: 2