Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Reverse Find in String

People also ask

How do you reverse part of a string in Python?

Strings can be reversed using slicing. To reverse a string, we simply create a slice that starts with the length of the string, and ends at index 0. The slice statement means start at string length, end at position 0, move with the step -1 (or one step backward).

What is Rfind () in Python?

The rfind() method finds the last occurrence of the specified value. The rfind() method returns -1 if the value is not found.

How do you find the part of a string in Python?

Python provides different ways and methods to generate a substring, to check if a substring is present, to get the index of a substring, and more. start - The starting index of the substring. stop - The final index of a substring. step - A number specifying the step of the slicing.


Your call tell rfind to start looking at index 34. You want to use the rfind overload that takes a string, a start and an end. Tell it to start at the beginning of the string (0) and stop looking at index:

>>> s = "Hello, I am 12! I like plankton but I don't like Baseball."
>>> index = 34 #points to the 't' in 'but'
>>> index_of_2nd_I = s.rfind('I', 0, index)
>>>
>>> index_of_2nd_I
16

I became curious how to implement looking n times for string from end by rpartition and did this nth rpartition loop:

orig = s = "Hello, I am 12! I like plankton but I don't like Baseball."
found = tail = ''
nthlast = 2
lookfor = 'I'
for i in range(nthlast):
    tail = found+tail
    s,found,end = s.rpartition(lookfor)
    if not found:
        print "Only %i (less than %i) %r in \n%r" % (i, nthlast, lookfor, orig)
        break
    tail = end + tail
else:
    print(s,found,tail)