Open In App

Find position of a character in given string – Python

Last Updated : 30 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string and a character, our task is to find the first position of the occurrence of the character in the string using Python. For example, consider a string s = “Geeks” and character k = ‘e’, in the string s, the first occurrence of the character ‘e’ is at index1. Let’s look at various methods of solving this problem:

Using Regular Expressions (re.search())

Regex (Regular Expressions) are patterns used to match sequences in text. With re.search(), we can find the first match of a pattern and get its position.

[GFGTABS]
Python

import re

s = 'Geeksforgeeks'
k = 'for'

match = re.search(k, s)
print("starting index", match.start())
print("start and end index", match.span())


[/GFGTABS]

Output

starting index 5
start and end index (5, 8)

Explanation:

  • re.search() returns the first match of the pattern.
  • .start() gives the index of the first character.
  • .span() gives a tuple (start, end) of the matched portion.

Using index()

The index() method returns the index of the first occurrence of a character. If not found, it raises a ValueError.

[GFGTABS]
Python

s = 'xyze'
k = 'b'

try:
    pos = s.index(k)
    print(pos)
except ValueError:
    print(-1)


[/GFGTABS]

Output

-1

Explanation:

  • index() finds the first occurrence and returns its index.
  • If the character isn’t found, it raises an error-handled using try-except.

Using a Loop

We can also manually loop through the string to find the first match.

[GFGTABS]
Python

s = 'GeeksforGeeks'
k = 'o'

res = -1
for i in range(len(s)):
    if s[i] == k:
        res = i
        break

print(res) 


[/GFGTABS]

Output

6

Explanation:

  • Loop checks each character.
  • If matched, it returns the index and exits early with break.

Using find()

find() method returns the index of the first match. If not found, it returns -1.

[GFGTABS]
Python

s1 = 'abcdef'
s2 = 'xyze'
k = 'b'

print(s1.find(k))  
print(s2.find(k))   


[/GFGTABS]

Output

1
-1

Explanation:

  • find() returns index of the first match.
  • If no match is found, it returns -1 instead of raising an error.

Using enumerate() with next()

This approach uses list comprehension and lazy evaluation to get the first index where the character matches.

[GFGTABS]
Python

def find_pos(s, k):
    try:
        return next(i for i, c in enumerate(s) if c == k)
    except StopIteration:
        return -1

s = 'xybze'
k = 'b'
print(find_pos(s, k))


[/GFGTABS]

Output

2

Explanation:

  • enumerate() gives index-character pairs.
  • next() returns the first matching index.
  • If not found, StopIteration is caught and -1 is returned.

Related articles:



Practice Tags :

Similar Reads