Search code examples
pythonfindletter

How to find last letter on word in string with find method?


Like the title says. I'm not working on high project or something but that question just wonders me.

Meri = "Meri: We are class"
Meri_1 = Meri.find('Meri')
print(Meri_1)

I would like to find the first and last letter on the word "Meri", that means to print 0 and 3.


Solution

  • Since you know the length of the string that you are trying to find the last letter of, you can do:

    search_string = "Meri"
    print(Meri.find(search_string) + len(search_string) - 1)
    

    All that this does is take the length of the string you are trying to find, add it to the index of the start of the string and then subtract 1 to get the last character of that string.

    Using the example that you have, Meri.find(search_string) will return 0 and when you add len(search_string) gives you 4, but because strings index at 0, you need to subtract 1 to give the correct index.