Find position of a character in given string Python (original) (raw)

Last Updated : 30 Apr, 2025

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:

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]

**Explanation:

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]

**Explanation:

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]

**Explanation:

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]

**Explanation:

Related articles: