Reputation: 73
I want to find all indexes of "a" item of my string, but it prints only the first one. What is the problem of this program:
def str_lookup_reverse(s, c):
for index in range(len(s)-1):
if s[index] == c:
print(index)
s = "parisa"
str_lookup_reverse(s, "a")
Upvotes: 2
Views: 66
Reputation: 26315
Very close. Your loop is ending too soon, you need to do loop over the indices of the whole string:
for index in range(len(s))
instead of:
for index in range(len(s)-1)
which loops over everything but the last character, where your second "a"
occurs. This means that your second "a"
never gets reached.
Additionally, a more pythonic way is to use enumerate()
:
def str_lookup_reverse(s, c):
for i, e in enumerate(s):
if e == c:
print(i)
s = "parisa"
str_lookup_reverse(s, "a")
Which also outputs what you want:
1
5
Upvotes: 1
Reputation: 7617
You could capture the index
by wrapping the String(s)
with enumerate()
as shown below.
def str_lookup_reverse(s, c):
index_list = []
for index, char in enumerate(s):
if char == c:
index_list.append(index)
# print(index)
return index_list
s = "parisa"
index_list = str_lookup_reverse(s, "a")
print(index_list) ## PRINTS: [1, 5]
Upvotes: 1
Reputation: 620
You can also just go through the characters like this -
def str_lookup_reverse(s, c):
ind = 0
for eachChar in s:
ind += 1
if eachChar == c:
print(ind)
s = "parisa"
str_lookup_reverse(s, "a")
Upvotes: 0
Reputation: 6578
You are using len(s)-1
, which will not iterate over the full length of the string. You should use len(s)
:
def str_lookup_reverse(s, c):
for index in range(len(s)):
if s[index] == c:
print(index)
s = "parisa"
str_lookup_reverse(s, "a")
To illustrate the problem, compare:
text='parisa'
for i in range(len(text)-1):
print("%s, %s") % (i, text[i])
0, p
1, a
2, r
3, i
4, s
With:
for i in range(len(text)):
print("%s, %s") % (i, text[i])
0, p
1, a
2, r
3, i
4, s
5, a
Upvotes: 2
Reputation: 27879
Have you tried it like this:
for i, letter in enumerate(s):
if letter == c:
print(i)
Upvotes: 4
Reputation: 42047
As others have mentioned your issue with for index in range(len(s)-1):
, which needs to be for index in range(len(s)):
.
Now, here's an approach with enumerate
:
[i for(i, v) in enumerate(s) if v == 'a']
e.g.
In [54]: s = "parisa"
In [55]: [i for(i, v) in enumerate(s) if v == 'a']
Out[55]: [1, 5]
As a function:
def findidx(string, char):
return [i for(i, v) in enumerate(string) if v == char]
e.g.
In [56]: def findidx(string, char):
....: return [i for(i, v) in enumerate(string) if v == char]
....:
In [57]: findidx(s, "a")
Out[57]: [1, 5]
Upvotes: 1
Reputation: 205
You're removing the length of the string... So you're removing the last a making s = 'paris'
def str_lookup_reverse(s, c):
for index in range(len(s)-1):
if s[index] == c:
print(index)
s = "parisa"
str_lookup_reverse(s, "a")
This will solve your problem:
def str_lookup_reverse(s, c):
for index in range(len(s)):
if s[index] == c:
print(index)
s = "parisa"
str_lookup_reverse(s, "a")
Upvotes: 2