Rosamunda
Rosamunda

Reputation: 14990

Python: How to print last X character found in a string? What´s wrong with my code that doesn´t always work?

I need to print the position of the last time I encounter a specific character, in a given string. How may I do that? ie. For this string "alahambra", I need to find the last time the letter "a" appears, so the result should be: 8.

I´ve tried this code, but it doesn´t always work:

def find_last(search, target):
    first=search.find(search)
    last=len(search)
    result=search.find(target,last-1)
    return result   

Examples:

print find_last('aaaaa', 'aa')

should print 3, and it prints -1 instead, that´s wrong!

print find_last('aaaa', 'b')

should print -1, and it prints -1, that´s correct.

print find_last("111111111", "1")

should print 8, and it prints 8, that´s correct.

print find_last("222222222", "")

should print 9, and it prints 8 instead, that´s wrong!

print find_last("", "3")

should print -1, and it prints -1, that´s correct.

print find_last("", "")

should print 0, and it prints 0, that´s correct.

What´s wrong in my code and how should I change it? Thanks!

Upvotes: 0

Views: 566

Answers (3)

rnbguy
rnbguy

Reputation: 1399

Your code should look like this :

>>> def find_last(A,q):
...     k = -1
...     while k < len(A):
...             i = A.find(q,k+1)
...             if i == -1: return k
...             else: k = i
...     return k
...
>>> find_last('aaaaa','aa')
3
>>> find_last("222222222", "")
9
>>> find_last("", "")
0
>>> find_last("", "3")
-1

Upvotes: 0

roman
roman

Reputation: 117530

you could use rindex or rfind - http://docs.python.org/2/library/string.html

"alahambra".rfind('a')

the difference between them is that rindex will raise error when the substring is not found and rfind will return -1

Upvotes: 1

zhangyangyu
zhangyangyu

Reputation: 8610

>>> "alahambra".rindex('a')
8
>>> 

This will raise an error if the substring is not found. Use rfind will return -1 in this case.

>>> "alahambra".rfind('a')
8
>>> 
>>> ''.rfind('b')
-1
>>> 

Upvotes: 6

Related Questions