A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/python-find-position-of-a-character-in-given-string/ below:

Find position of a character in given string - Python

Find position of a character in given string - Python

Last Updated : 11 Jul, 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.

Python
import re

s = 'Geeksforgeeks'
k = 'for'

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

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.

Python
s = 'xyze'
k = 'b'

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

Explanation:

Using a Loop

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

Python
s = 'GeeksforGeeks'
k = 'o'

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

print(res) 

Explanation:

Using find()

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

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

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

Explanation:

Using enumerate() with next()

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

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))

Explanation:

Related articles:



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4