Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Replace a String character at given index in Python
Next article icon

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:

  • rfind() method
  • re.search() method
  • enumerate() method
  • next()


Next Article
Replace a String character at given index in Python
author
garg_ak0109
Improve
Article Tags :
  • Python
  • Python Programs
  • Python string-programs
Practice Tags :
  • python

Similar Reads

  • Python | Get positional characters from String
    Sometimes, while working with Python strings, we can have a problem in which we need to create a substring by joining the particular index elements from a string. Let's discuss certain ways in which this task can be performed. Method #1: Using loop This is a brute method in which this task can be pe
    5 min read
  • Python | Longest Run of given Character in String
    Sometimes, while working with Strings, we can have a problem in which we need to perform the extraction of length of longest consecution of certain letter. This can have application in web development and competitive programming. Lets discuss certain ways in which this task can be performed. Method
    6 min read
  • Iterate over characters of a string in Python
    In this article, we will learn how to iterate over the characters of a string in Python. There are several methods to do this, but we will focus on the most efficient one. The simplest way is to use a loop. Let’s explore this approach. Using for loopThe simplest way to iterate over the characters in
    2 min read
  • Get Last N characters of a string - Python
    We are given a string and our task is to extract the last N characters from it. For example, if we have a string s = "geeks" and n = 2, then the output will be "ks". Let's explore the most efficient methods to achieve this in Python. Using String Slicing String slicing is the fastest and most straig
    2 min read
  • Replace a String character at given index in Python
    In Python, strings are immutable, meaning they cannot be directly modified. We need to create a new string using various methods to replace a character at a specific index. Using slicingSlicing is one of the most efficient ways to replace a character at a specific index. [GFGTABS] Python s = "h
    2 min read
  • Python - Strings with all given List characters
    GIven Strings List and character list, extract all strings, having all characters from character list. Input : test_list = ["Geeks", "Gfg", "Geeksforgeeks", "free"], chr_list = [ 'f', 'r', 'e'] Output : ['free', "Geeksforgeeks"] Explanation : Only "free" and "Geeksforgeeks" contains all 'f', 'r' and
    4 min read
  • Split String into List of characters in Python
    We are given a string and our task is to split this string into a list of its individual characters, this can happen when we want to analyze or manipulate each character separately. For example, if we have a string like this: 'gfg' then the output will be ['g', 'f', 'g']. Using ListThe simplest way
    2 min read
  • Python - Least Frequent Character in String
    The task is to find the least frequent character in a string, we count how many times each character appears and pick the one with the lowest count. Using collections.CounterThe most efficient way to do this is by using collections.Counter which counts character frequencies in one go and makes it ea
    3 min read
  • Python program to find occurrence to each character in given string
    Given a string, the task is to write a program in Python that prints the number of occurrences of each character in a string. There are multiple ways in Python, we can do this task. Let's discuss a few of them. Method #1: Using set() + count() Iterate over the set converted string and get the count
    5 min read
  • Count the number of characters in a String - Python
    The goal here is to count the number of characters in a string, which involves determining the total length of the string. For example, given a string like "GeeksForGeeks", we want to calculate how many characters it contains. Let’s explore different approaches to accomplish this. Using len()len() i
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences