Table of Contents
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
ifstatement to check if the returned index is not-1; if so, print that index; otherwise, print an error.
|
1 2 3 4 5 6 7 8 9 10 |
my_string = "character" character = 'a' if my_string.find(character) != -1: print(f'\'{character}\' in \'{my_string}\'' f' exists at index {my_string.find(character)}') else: print(f'\'{character}\' does not exist in \'{my_string}\'') |
On execution of the program, we will get the following output.
|
1 2 3 |
'a' in 'character' exists at index 2 |
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
substringargument is required and used to search it in the given string. - The
startandendarguments are optional and specify the starting and ending indexes from which to search for thesubstring. If these arguments are not specified, then it searches from0(the beginning) tolen(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:
|
1 2 3 4 5 6 7 8 9 10 |
my_string = "character" character = 'c' if my_string.find(character, 2, 5) != -1: print(f'\'{character}\' in \'{my_string}\'' f' exists at index {my_string.find(character, 2, 5)}') else: print(f'\'{character}\' does not exist in \'{my_string}\'') |
The program will print the following output on the console:
|
1 2 3 |
'c' does not exist in 'character' |
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 suppliedcharacterin input string. - Use the
try-exceptclause to handle the exception of no match.
|
1 2 3 4 5 6 7 8 9 |
my_string = "character" character = 'a' try: print(f'\'{character}\' in \'{my_string}\'' f' exists at index {my_string.index(character)}') except Exception as e: print(e) |
When we execute the program, we will get the following output.
|
1 2 3 |
'a' in 'character' exists at index 2 |
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:
|
1 2 3 4 5 6 7 8 9 |
my_string = "character" character = 'c' try: print(f'\'{character}\' in \'{my_string}\'' f' exists at index {my_string.index(character, 2, 5)}') except Exception as e: print(e) |
Now we will get the following output:
|
1 2 3 |
substring not found |
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.
Further reading:
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
inkeyword to test if input string contains the suppliedcharacter. - Use
re.finditer()to create a new list of all matches of thecharacterinstring. - Use the
forloop to iterate over everyelementof the new list. - Inside the
forloop, useelement.start()to get the indexes of every occurrence.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
import re my_string = "character" character = 'a' if character in my_string: print(f'\'{character}\' is located in \'{my_string}\' at indexes:') for element in re.finditer(character, my_string): print(element.start()) else: print(f'\'{character}\' does not exist in \'{my_string}\'') |
On execution, the above code will print the following output on the console:
|
1 2 3 4 5 |
'a' is located in 'character' at indexes: 2 4 |
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.
|
1 2 3 4 5 6 7 8 |
def findOccurrences(s, ch): return [i for i, character in enumerate(s) if character == ch] str = "Java2blog" ch ='a' print(findOccurrences(str,ch)) |
|
1 2 3 |
[1,3] |
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.