OneBite.Dev - Coding blog in a bite size

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

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

  def find_first_occurrence(string, char): 
    index = 0
  
    while index < len(string): 
        if string[index] == char: 
            return index 
        index += 1
  
    return -1

This code defines a function called find_first_occurrence. This function takes two arguments: a string and a single character. It then iterates through the string one character at a time, starting from the first character, checking to see if the character matches the argument char. If a match is found, the loop stops and the index number corresponding to the first occurrence of the character is returned. If no matches are found, -1 is returned to indicate that the character is not present in the string. This can be used to find the first occurrence of any character in a string.

python