2012-03-05 12 views

Respuesta

311

Uso .rfind():

>>> s = 'hello' 
>>> s.rfind('l') 
3 

Tampoco utilice str como nombre de variable o te sombra la incorporada en str().

30

Utilice el método str.rindex.

>>> 'hello'.rindex('l') 
3 
>>> 'hello'.index('l') 
2 
1

Prueba esto:

s = 'hello plombier pantin' 
print (s.find('p')) 
6 
print (s.index('p')) 
6 
print (s.rindex('p')) 
15 
print (s.rfind('p')) 
42

Usted puede utilizar rfind() o rindex()
enlaces python2: rfind()rindex()

s = 'Hello StackOverflow Hi everybody' 

print(s.rfind('H')) 
20 

print(s.rindex('H')) 
20 

print(s.rfind('other')) 
-1 

print(s.rindex('other')) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
ValueError: substring not found 

La diferencia es cuando no se encuentra la subcadena, rfind() devoluciones -1 mientras que rindex() plantea una excepción ValueError (enlace Python2: ValueError).

Si no desea comprobar el código de retorno rfind()-1, es posible que prefiera rindex() que proporcionará un mensaje de error comprensible. De lo contrario puede buscar minutos donde el valor inesperado -1 proviene de dentro de su código ...

1

La biblioteca more_itertools ofrece herramientas para la búsqueda de caracteres y subcadenas:

s = "hello" 
list(mit.locate(s, lambda x: x == "l"))[-1] 
# 3 

s = "How much wood would a woodchuck chuck if a woodchuck could chuck wood?" 
substring = "chuck" 
pred = lambda w: w == tuple(substring) 
list(mit.locate(mit.windowed(s, len(substring)), pred=pred))[-1] 
# 59 

Documentación para herramientas discutidas: locate, windowed .

0

Si usted no quiere utilizar rfind entonces esto va a hacer el truco/

def find_last(s, t): 
    last_pos = -1 
    while True: 
     pos = s.find(t, last_pos + 1) 
     if pos == -1: 
      return last_pos 
     else: 
      last_pos = pos 
Cuestiones relacionadas