Find Character in String in Python

Using find() Method

To find the character in a string in Python:

  • Use the find() method to find the index of the first occurrence of the supplied character in the input String.
  • Use an if statement to check if the returned index is not -1; if so, print that index; otherwise, print an error.

On execution of the program, we will get the following output.

The find() is a built-in method in Python that searches for a substring in a string. It returns the index of the first occurrence of the substring or -1 if not found. It holds:

  • The substring argument is required and used to search it in the given string.
  • The start and end arguments are optional and specify the starting and ending indexes from which to search for the substring. If these arguments are not specified, then it searches from 0 (the beginning) to len(string)-1 (the end).

We applied the find() method on my_string to get an index of the first matched occurrence of the character.

We used an if statement to handle the returned value of -1. If the find() method returned -1, we printed the index of the matched occurrence. Otherwise, the program jumped to the else statement.

If we specify the start and end as:

The program will print the following output on the console:

Now the find() method searched the first occurrence of the character in my_string from start=2 to end=5, i.e., ara (excluding the fifth index). As no character=c, the program jumped on the else block and printed the error message.

Using index() Method

To locate the character in a string in Python:

  • Use the index() method to find the index of the first occurrence of the supplied character in input string.
  • Use the try-except clause to handle the exception of no match.

When we execute the program, we will get the following output.

The index() is a built-in method in Python and is like the find() method that we discussed earlier when explaining the code snippet using the find() method. But it raises an exception called ValueError when it does not find any match.

We applied the index() method on my_string to get an index of the first matched occurrence of the character.

To handle the exception, we used a try-except statement. When no exception occurred, the try clause successfully printed the index of the first occurrence of the character in my_string. In case of an exception, the program jumped to the except clause to print the reason for the exception.

To specify the start and end in the index() method:

Now we will get the following output:

Now, after specifying start=2 and end=5, the index() method did not find any occurrence of the character. So, the program jumped to the except statement. The except statement excepted the Exception returned by the index() method as e. Inside the clause, we printed the ValueError.

Until this point, we have learned about finding a character's first occurrence in a string. Next, learn to find multiple occurrences of a character` in a string.

Using for Loop with re.finditer() Method

To get the multiple occurrences frequency of a character in a string:

  • Import Python library re.
  • Use the in keyword to test if input string contains the supplied character.
  • Use re.finditer() to create a new list of all matches of the character in string.
  • Use the for loop to iterate over every element of the new list.
  • Inside the for loop, use element.start() to get the indexes of every occurrence.

On execution, the above code will print the following output on the console:

The in keyword is a Python operator that tests if an iterable object container contains a specific value and is equivalent to the contains() method of the built-in str module.

We place an infix operator between two operands: the value to be tested and the sequence to test it against. It does not return any index, but True if the value exists, and False if not.

We used the in operator taking character and my_string as operands. If the character appeared in my_string, we used the if statement to run the further program. Otherwise, the else statement printed a message of no match.

We imported the re library, a Python regular expression library. It provides regular expression matching operations to support string-processing functions.

The re library provides the re.finditer() method that finds all occurrences of a pattern in a string. It creates a match object for each occurrence, and each object contains a count of the character positions in the string that the pattern matched. Finally, it returns an iterator of match objects.

We used the re.finditer() to create match objects of the occurrences of the character in my_string and used the for loop to iterate over every element of re.finditer().

Inside the for loop, we printed the index of every occurrence using the element.start() method.

Using list comprehension

To find multiple occurrences of character in String:

  • Use list comprehension to iterate over each character of given String with enumerate().
  • For each character, compare it with given character.
  • If condition is met, return the index.
  • Result will be list of the indices of character in the String.

We defined custom function named findOccurrences() which takes input as String and character.

We used enumerate() function to get index of current iteration.

enumerate() function takes a iterable as input and returns tuple with first element as index and second element as the corresponding item.

On each iteration, we checked if current character is equal to a. If yes, we returned that index.

Resultant list contains all the indexes of character in the String.

That’s all about how to find character in String in Python.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *