Home > Back-end >  How to find the index of the last character of a substring in python
How to find the index of the last character of a substring in python

Time:01-16

How to find the index of the last character of a substring in python Eg : s = "hello"
index of the last character 'e' in s.find("he")

CodePudding user response:

You can do this simply by -

string = "hello"
subStr = "he"
if (string.find(subStr) != -1):
    print(string[string.find(subStr) len(subStr)-1])

else:
    print("Substring not found")

CodePudding user response:

if substr in s:
    idx = s.find(substr)   len(substr) - 1
    print(s[idx])

In your case substr = 'he'

s.find() returns index of first symbol of substring. You need to add len(substr) - 1 to get index of last symbol of substring

CodePudding user response:

That's should do

def get_index(s,substring):
    start = s.find(substring)
    if(start != -1):
        return start   len(substring) - 1
    else:
        print("substring not found")
  •  Tags:  
  • Related