OneBite.Dev - Coding blog in a bite size

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

Code snippet on how to find the last occurrence of a character in a string in python

def last_occurrence(s, target):
  index = -1
  while True:
    index = s.find(target, index+1) 
    if index == -1:
      break
  return index

The code starts by defining a function named “last_occurrence” with two parameters: “s” (the string where we are looking for the last occurrence of a character), and “target” (the character we are looking for). The function then sets a variable called “index” to the value -1, which indicates the character is not found. The code then enters an infinite loop, which searches for the character in the string starting from the index +1. If the character is not found, the loop breaks, and the function returns the index.

python