Python - How To Find Character in a String in Python

ID : 83

viewed : 122

Tags : PythonPython String

vote vote

94

Strings are a collection of characters. Each character in the string has some specific position that can be used to access it. In this tutorial, we will discuss how to find the position of a character in a string.

Use the find() Function to Find the Position of a Character in a String

The find() function returns the position of a substring. We can also specify the start and end positions in which we want to search (by default, the start is 0, and the end is the string’s length).

In the following code, we will use this function to find the position of a character in a string.

s = 'python is fun' c = 'n' print(s.find(c)) 

Output:

5 

Note that it returns the first position of the character encountered in the string. Another thing to remember about this function is that it returns -1 when the given substring is not present in the string.

Use the rfind() Function to Find the Position of a Character in a String

This function is similar to the find() function, with the only difference being that it returns the last position of the substring.

For example,

s = 'python is fun' c = 'n' print(s.rfind(c)) 

Output:

12 

Use the index() Function to Find the Position of a Character in a String

The index() function is used similarly to the find() function to return the position of characters in a string. Like the find() function, it also returns the first occurrence of the character in the string.

For example,

s = 'python is fun' c = 'n' print(s.index(c)) 

Output:

5 

The difference between the index() and find() function is that the index() function returns ValueError when the required character is missing from the string.

Use the for Loop to Find the Position of a Character in a String

In this method, we can note every occurrence of the character in a string. We iterate through the string and compare each character individually. Every position where the match is found is indicated and stored in a different variable.

The following code implements this logic.

s = 'python is fun' c = 'n' lst = [] for pos,char in enumerate(s):     if(char == c):         lst.append(pos) print(lst) 

Output:

[5, 12] 

We use the enumerate() function because it makes the iteration easier and assigns a counter variable with every character of the string.

We can also implement this method using the list comprehension method, which is considered faster and cleaner.

For example,

s = 'python is fun' c = 'n' print([pos for pos, char in enumerate(s) if char == c]) 

Output:

[5, 12] 

  • Related HOW TO?