Reputation: 33
I know that to get the index of a character from the end of a string, you do:
str.index(sub, -1)
So why does this code produce and error when I call it?
def test(string):
for letter in string:
print string.index(letter, -1)
Thanks.
Upvotes: 1
Views: 236
Reputation: 882078
I know that to get the index of a character from the end of a string, ...
I think you may be confused here, it does not get the index from the end of the string, it gets the index from the start of the string, but only starts searching from the given index.
This becomes evident if you enter and run the following code:
def test(string):
for letter in 'e':
print string.index(letter, -1)
test("abcde")
and you correctly get 4
as the output, the position of e
from the string start.
In your code (and the example above), we are telling it to search the substring starting at index -1
, which is just the last character in the string.
So, if your string is "abc"
, it will first look for a
in the substring "c"
and, not finding it, will raise an exception.
Changing your code to:
def test(string):
for letter in string:
print string.index(letter)
test("abcde")
will give you the correct indexes without raising an exception.
If you do need the index from the end of the string (so that e
is 0
and a
is 4
), some simple mathematical manipulation will do it:
def test(string):
for letter in string:
print len(string) - string.index(letter, 0) - 1
test("abcde")
This code gives you, for the letters a
through e
:
4
3
2
1
0
Upvotes: 1
Reputation: 53607
read here http://www.tutorialspoint.com/python/string_index.htm or https://docs.python.org/2/library/string.html#string.find
It did not find it in the location u specified to look for it.
Regardless, try-catch it and see the error.
Upvotes: 0