find the last index of a character in a string in python

There are multiple ways to find the last index of a character in a string in python. One way is to use the rfind() method.

main.py
my_string = "hello world"
char = 'l'
last_index = my_string.rfind(char)
print(last_index) # output: 9
102 chars
5 lines

Another way is to reverse the string and use the find() method.

main.py
my_string = "hello world"
char = 'l'
last_index = len(my_string) - my_string[::-1].find(char) - 1
print(last_index) # output: 9
128 chars
5 lines

Both methods have their advantages and disadvantages, so choose the one that fits your needs best.

gistlibby LogSnag