How to find the position of a character in a given string in Python

In this tutorial, we will learn how to find the position of a character in a given string with Python.

In order to get the position of a character in a given string, we are going to use 3 methods. We are going to see examples of each of these methods. So keep reading this article…

Let us learn the methods:

1) Naive method:

This is one of the methods to get the position of a character in a given string.

In this method first, the variable which stores the position of a character is initialized to None.

Then, every character in a string with its index is compared with the character for which the position has to be found.

If any of the characters in a string is the same as the input character, then the variable i.e., which stores the position of a character is incremented by one.

Then, the position variable is compared. If the variable contains a None value, then the input character is not found in a string. Otherwise, it prints the position of the character.

Let’s see an example program:

given_string = 'codespeedy'
   
char = "s" 

pos = None
for i in range(0, len(given_string)): 
    if given_string[i] == char: 
        pos = i + 1
        break
      
if pos == None: 
    print ("character is not available in string") 
else:  
    print ("Character {} is present at position {}".format(char, str(pos)))

output:

Character s is present at position 5

Also, read: How to get the last word from a string in Python?

2) find()

We can use this Python method also to find the position of a character in a given string.

find() method takes the character for which position has to be found as a parameter.

How to check whether the character is present in a string or not using find()?

The answer is, the find() method returns -1 if the character is not present in the given string.

Let’s see the program:

given_string = 'codespeedy'
   
char = "s" 

pos = given_string.find(char)
      
if pos == -1: 
    print ("character is not available in string") 
else:  
    print ("Character {} is present at position {}".format(char, str(pos+1)))

output:

Character s is present at position 5

3) index()

This method is the same as the find() method. It also takes the character for which position has to be found as a parameter to the index() method.

This index() method raises ValueError if the character is not present in the string. so, not to get an error while working on it, we will handle it by using try and except blocks.

given_string = 'codespeedy'
   
char = "s" 

try :
   pos = given_string.index(char)
   print ("Character {} is present at position {}".format(char, str(pos+1)))
except ValueError as e : 
    print ("character is not available in string") 
 

output:

Character s is present at position 5

 

Leave a Reply

Your email address will not be published.