Python program to determine the position of character in a string using index

In this post, we discuss the following methods to determine the position of character in a string using the index.

Using Python String index() Method

Using Python String find() Method

Using Python String rfind() Method

Using List Comprehension

Using the for Loop

Using Python String index() Method

The String index() method returns the index/ position of first occurrence of the character in the string.

Example

In the program below, we find the position of the character y in the given string.

str = "Binary Study Python Programming made easy"
char = 'y'
pos = str.index(char)
print(pos)

Output

5

Note that in the given string "Binary Study Python Programming made easy", there are four y but the index() method returns the index of first y.

Using Python String find() Method

Same as the index method, the String find() method also returns the index of first occurrence of the character in the string.

Example

In the program below, we find the position of the character y in the given string.

str = "Binary Study Python Programming made easy"
char = 'y'
pos = str.find(char)
print(pos)

Output

5

Using Python String rfind() Method

The String rfind() method returns the index/ position of the last occurrence of the character in the string. 

Example

In the program below, we find the position of the character y in the given string.

str = "Binary Study Python Programming made easy"
char = 'y'
pos = str.rfind(char)
print(pos)

Output

40

Notice that rfind() method returns the position of the last char in the string.

Using List Comprehension

We could apply the list comprehension to find the position of the character in the string.

Example

str = "Binary Study Python Programming made easy"
ch = 'y'
pos = [pos for pos, char in enumerate(strif char == ch ]
print(pos)

Output

[5, 11, 14, 40]

Note that using the list comprehension we found all the positions of the character in the string.

Using the for Loop

We loop through all the characters in the string and compare one by one with the given character. If match found we print the position. 

Example

str = "Binary Study Python Programming made easy"
ch = 'y'
for pos, char in enumerate(str):
    if char == ch:
        print(f"{pos}")
    else:
        pass

Output

5
11
14
40

Note that using the for loop, we found all the positions of the character in the string.

You may be interested in the following posts:

Comments