How do you find the index of an element in a string in python from the last?

I want to find the position (or index) of the last occurrence of a certain substring in given input string str.

For example, suppose the input string is str = 'hello' and the substring is target = 'l', then it should output 3.

How can I do this?

How do you find the index of an element in a string in python from the last?

asked Mar 5, 2012 at 19:13

How do you find the index of an element in a string in python from the last?

Use .rfind():

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

Also don't use str as variable name or you'll shadow the built-in str().

answered Mar 5, 2012 at 19:15

Rik PoggiRik Poggi

27.3k6 gold badges63 silver badges81 bronze badges

0

You can use rfind() or rindex()
Python2 links: 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

The difference is when the substring is not found, rfind() returns -1 while rindex() raises an exception ValueError (Python2 link: ValueError).

If you do not want to check the rfind() return code -1, you may prefer rindex() that will provide an understandable error message. Else you may search for minutes where the unexpected value -1 is coming from within your code...


Example: Search of last newline character

>>> txt = '''first line
... second line
... third line'''

>>> txt.rfind('\n')
22

>>> txt.rindex('\n')
22

answered Nov 14, 2014 at 10:51

How do you find the index of an element in a string in python from the last?

oHooHo

47.4k27 gold badges156 silver badges192 bronze badges

1

Use the str.rindex method.

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

answered Mar 5, 2012 at 19:15

rmmhrmmh

6,90125 silver badges37 bronze badges

1

Not trying to resurrect an inactive post, but since this hasn't been posted yet...

(This is how I did it before finding this question)

s = "hello"
target = "l"
last_pos = len(s) - 1 - s[::-1].index(target)

Explanation: When you're searching for the last occurrence, really you're searching for the first occurrence in the reversed string. Knowing this, I did s[::-1] (which returns a reversed string), and then indexed the target from there. Then I did len(s) - 1 - the index found because we want the index in the unreversed (i.e. original) string.

Watch out, though! If target is more than one character, you probably won't find it in the reversed string. To fix this, use last_pos = len(s) - 1 - s[::-1].index(target[::-1]), which searches for a reversed version of target.

answered Apr 7, 2018 at 14:17

Adi219Adi219

4,4842 gold badges19 silver badges42 bronze badges

2

Try this:

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

Chei

2,0773 gold badges20 silver badges32 bronze badges

answered Oct 13, 2014 at 14:10

GadGad

691 silver badge2 bronze badges

The more_itertools library offers tools for finding indices of all characters or all substrings.

Given

import more_itertools as mit


s = "hello"
pred = lambda x: x == "l"

Code

Characters

Now there is the rlocate tool available:

next(mit.rlocate(s, pred))
# 3

A complementary tool is locate:

list(mit.locate(s, pred))[-1]
# 3

mit.last(mit.locate(s, pred))
# 3

Substrings

There is also a window_size parameter available for locating the leading item of several items:

s = "How much wood would a woodchuck chuck if a woodchuck could chuck wood?"
substring = "chuck"
pred = lambda *args: args == tuple(substring)

next(mit.rlocate(s, pred=pred, window_size=len(substring)))
# 59

answered Feb 9, 2018 at 2:23

How do you find the index of an element in a string in python from the last?

pylangpylang

36.2k11 gold badges120 silver badges110 bronze badges

For this case both rfind() and rindex() string methods can be used, both will return the highest index in the string where the substring is found like below.

test_string = 'hello'
target = 'l'
print(test_string.rfind(target))
print(test_string.rindex(target))

But one thing should keep in mind while using rindex() method, rindex() method raises a ValueError [substring not found] if the target value is not found within the searched string, on the other hand rfind() will just return -1.

answered Nov 14, 2021 at 9:30

How do you find the index of an element in a string in python from the last?

RubelRubel

1,01811 silver badges17 bronze badges

Python String rindex() Method

Description
Python string method rindex() returns the last index where the substring str is found, or raises an exception if no such index exists, optionally restricting the search to string[beg:end].

Syntax
Following is the syntax for rindex() method −

str.rindex(str, beg=0 end=len(string))

Parameters
str − This specifies the string to be searched.

beg − This is the starting index, by default its 0

len − This is ending index, by default its equal to the length of the string.

Return Value
This method returns last index if found otherwise raises an exception if str is not found.

Example
The following example shows the usage of rindex() method.

Live Demo

!/usr/bin/python

str1 = "this is string example....wow!!!";
str2 = "is";

print str1.rindex(str2)
print str1.index(str2)

When we run above program, it produces following result −

5
2

Ref: Python String rindex() Method - Tutorialspoint

answered Jun 15, 2020 at 10:12

How do you find the index of an element in a string in python from the last?

If you don't wanna use rfind then this will do the trick/

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

answered Feb 23, 2018 at 17:15

How do you find the index of an element in a string in python from the last?

SalamSalam

87512 silver badges18 bronze badges

# Last Occurrence of a Character in a String without using inbuilt functions
str = input("Enter a string : ")
char = input("Enter a character to serach in string : ")
flag = 0
count = 0
for i in range(len(str)):
    if str[i] == char:
        flag = i
if flag == 0:
    print("Entered character ",char," is not present in string")
else:
    print("Character ",char," last occurred at index : ",flag)

answered Jun 5, 2021 at 21:29

ChandChand

111 bronze badge

you can use rindex() function to get the last occurrence of a character in string

s="hellloooloo"
b='l'
print(s.rindex(b))

taras

6,24210 gold badges38 silver badges48 bronze badges

answered Oct 7, 2019 at 10:36

How do you find the index of an element in a string in python from the last?

str = "Hello, World"
target='l'
print(str.rfind(target) +1)

or

str = "Hello, World"
flag =0
target='l'
for i,j in enumerate(str[::-1]):
    if target == j:
       flag = 1
       break;
if flag == 1:   
    print(len(str)-i)

answered Jan 12 at 7:26

How do you find the index at the end of a string in Python?

5 Ways to Find the Index of a Substring in Strings in Python.
str.find().
str.rfind().
str.index().
str.rindex().
re.search().

How do I get the last index of a string?

The lastIndexOf() method returns the index (position) of the last occurrence of a specified value in a string. The lastIndexOf() method searches the string from the end to the beginning. The lastIndexOf() method returns the index from the beginning (position 0).

How do you find the index of a substring within a string in Python?

Python String find() method returns the lowest index or first occurrence of the substring if it is found in a given string. If it is not found, then it returns -1.

How do you find the index of a specific string?

Java String indexOf() Method The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.