Find index of last occurrence of a substring in a string

前端 未结 9 1469
挽巷
挽巷 2020-11-27 10:36

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

相关标签:
9条回答
  • 2020-11-27 10:46

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

    s="hellloooloo"
    b='l'
    print(s.rindex(b))
    
    0 讨论(0)
  • 2020-11-27 10:47

    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

    0 讨论(0)
  • 2020-11-27 11:03

    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'))
    
    0 讨论(0)
提交回复
热议问题