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:
Get Last N characters of a string - Python
Next article icon

Python – Extract String after Nth occurrence of K character

Last Updated : 26 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a String, extract the string after Nth occurrence of a character. 

Input : test_str = ‘geekforgeeks’, K = “e”, N = 2 
Output : kforgeeks 
Explanation : After 2nd occur. of “e” string is extracted. 

Input : test_str = ‘geekforgeeks’, K = “e”, N = 4 
Output : ks 
Explanation : After 4th occur. of “e” string is extracted.

Method #1 : Using split()

This is one of the ways in which this task can be performed. In this we customize split() to split on Nth occurrence and then print the rear extracted string using “-1”.

Python3




# Python3 code to demonstrate working of
# Extract String after Nth occurrence of K character
# Using split()
 
# initializing string
test_str = 'geekforgeeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing K
K = "e"
 
# initializing N
N = 3
 
# using split() to perform required string split
# "-1" to extract required part
res = test_str.split(K, N)[-1]
 
# printing result
print("The extracted string : " + str(res))
 
 
Output
The original string is : geekforgeeks The extracted string : eks

Time complexity: O(n), where n is the length of the input string.
Auxiliary space: O(n).

Method #2 : Using re.split()

This is yet another way to solve this problem. Similar to above function, we perform split() to perform task of splitting but from regex library which also provides flexibility to split on Nth occurrence.

Python3




# Python3 code to demonstrate working of
# Extract String after Nth occurrence of K character
# Using re.split()
import re
 
# initializing string
test_str = 'geekforgeeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing K
K = "e"
 
# initializing N
N = 3
 
# using split() to perform required string split
# "-1" to extract required part
res = re.split(K, test_str, N)[-1]
 
# printing result
print("The extracted string : " + str(res))
 
 
Output
The original string is : geekforgeeks The extracted string : eks

Time Complexity: O(n), where n is the length of the input string ‘test_str’. 
Auxiliary Space: O(n), where n is the length of the input string ‘test_str’. 

Method #3 : Using slicing

Python3




str = "geeksforgeeks"
char="e"
count=2
j=1
print("The original string : "+str)
for i in range(0,len(str)):
    if(str[i]==char and j<count):
        j+=1
    elif(str[i]==char and j==count):
        print("The extracted string : "+str[i+1:])
        break
 
 
Output
The original string : geeksforgeeks The extracted string : ksforgeeks

Time Complexity: O(n)
Auxiliary Space: O(n)

Method 4: Using try-except and index()

  1. Define a function named extract_string that takes three arguments, a test string (test_str), a character (K) and an integer (N).
  2. Initialize a variable named index with value 0.
  3. Loop through the range of N using a for loop:
    a. Inside the for loop, use the index() method on test_str with K and index as the starting index to get the index of Nth occurrence of K.
    b. Update the value of index with the index of Nth occurrence of K + 1.
  4. Use slicing to extract the string after Nth occurrence of K and return it.
  5. If there are not enough occurrences of K in the string, the index() method will raise a ValueError. Catch the exception using a try-except block.
  6. If the exception is caught, return -1.

Python3




def extract_string(test_str, K, N):
    try:
        # Finding the index of Nth occurrence of K
        index = 0
        for i in range(N):
            index = test_str.index(K, index) + 1
        # Extracting the string after Nth occurrence of K
        return test_str[index:]
    except Exception as e:
        # If there are not enough occurrences of K in the string
        return -1
#Testing the code
test_str = 'geekforgeeks'
K = "e"
N = 2
print("The extracted string : " + extract_string(test_str, K, N))
 
 
Output
The extracted string : kforgeeks

Time Complexity: O(N*K), where N is the value of N and K is the average length of the substring between two occurrences of K in the test_str. The loop runs N times and, in each iteration, it searches for the next occurrence of K in the substring of test_str, which has an average length of K.

Auxiliary Space: O(1), which means it uses a constant amount of extra memory to execute. This is because the algorithm only stores the index of Nth occurrence of K and the extracted substring in memory, and these variables have constant size regardless of the input size.

 Method #5: Using the string method find() and string slicing.

1-Initialize the input string test_str, the character to find K, and the Nth occurrence N.
2-Initialize a variable index to 0 and a variable count to 0.
3-While count is less than N:
  a. Find the index of the K character in test_str starting from the index position using the find()      method.
  b. If the find() method returns -1, exit the loop.
  c. Otherwise, increment count by 1 and update the value of index to index + 1.
4-Extract the substring from test_str starting from the index position to the end of the string using slicing.
5-Print the extracted substring.

Python3




# Python3 code to demonstrate working of
# Extract String after Nth occurrence of K character
# Using find() and slicing
 
# initializing string
test_str = 'geekforgeeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing K
K = "e"
 
# initializing N
N = 3
 
# using find() and slicing to perform required string extraction
index = 0
for i in range(N):
    index = test_str.find(K, index) + 1
res = test_str[index:]
 
# printing result
print("The extracted string : " + str(res))
 
 
Output
The original string is : geekforgeeks The extracted string : eks

Time complexity: O(N * M), where N is the value of N and M is the length of the input string test_str. 
Auxiliary space: O(1), as the program uses only a constant amount of extra memory to store the variables index, K, N, and res..

Method #6: Using for loop and slicing

Step-by-step approach:

  • Find all occurrences (indices) of K in string using for loop
  • Slice the string 3rd occurrence index to end
  • Display the sliced string

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Extract String after Nth occurrence of K character
 
# initializing string
test_str = 'geekforgeeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing K
K = "e"
 
# initializing N
N = 3
v=[]
for i in range(0,len(test_str)):
    if(test_str[i]==K):
        v.append(i)
res=test_str[v[N-1]:]
# printing result
print("The extracted string : " + str(res))
 
 
Output
The original string is : geekforgeeks The extracted string : eeks

Time Complexity : O(N)
Auxiliary Space : O(1)

Method 7 : Using List Comprehension and Enumerate()

Initialize the test string.
Initialize the K character and N value.
Use list comprehension to iterate over the string and store the index of each occurrence of the K character.
Use the enumerate() function to iterate over the list of indices and select the index of the Nth occurrence of the K character.
Use slicing to extract the string after the matched K character.
If the Nth occurrence of the K character is not found, print an error message.

Python3




# Python3 code to demonstrate working of
# Extract String after Nth occurrence of K character
# Using list comprehension and enumerate()
 
# initializing string
test_str = 'geekforgeeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing K
K = "e"
 
# initializing N
N = 3
 
# list comprehension to get the indices of K character
indices = [i for i, x in enumerate(test_str) if x == K]
 
# extracting string after Nth occurrence of K character
if len(indices) >= N:
    res = test_str[indices[N-1]+1:]
    print("The extracted string : " + str(res))
else:
    print("Error: K character not found N times in the string.")
 
 
Output
The original string is : geekforgeeks The extracted string : eks 

Time complexity: O(n), where n is the length of the string.
Auxiliary space: O(m), where m is the number of occurrences of the K character in the string.



Next Article
Get Last N characters of a string - Python
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python string-programs
Practice Tags :
  • python

Similar Reads

  • Split string on Kth Occurrence of Character - Python
    The task is to write Python program to split a given string into two parts at the Kᵗʰ occurrence of a specified character. If the character occurs fewer than K times return the entire string as the first part and an empty string as the second part. For example, in the string "a,b,c,d,e,f", splitting
    3 min read
  • Python - Extract String till all occurrence of characters from other string
    Given a string, the task is to write a Python program to extract till all characters from other strings are found. Input : test_str = "geeksforgeeks is best for all geeks", check_str = "freak"Output : geeksforgeeks is best for aExplanation : a is last letter in freak to be present in string. The str
    11 min read
  • Python | Replace characters after K occurrences
    Sometimes, while working with Python strings, we can have a problem in which we need to perform replace of characters after certain repetitions of characters. This can have applications in many domains including day-day and competitive programming. Method #1: Using loop + string slicing This is brut
    5 min read
  • Python - Characters Index occurrences in String
    Sometimes, while working with Python Strings, we can have a problem in which we need to check for all the characters indices. The position where they occur. This kind of application can come in many domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using set() + reg
    6 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
  • Python | First character occurrence from rear String
    There are many ways to find out the first index of element in String as python in its language provides index() function that returns the index of first occurrence of element in String. But if one desires to get the last occurrence of element in string, usually a longer method has to be applied. Let
    4 min read
  • Python | Extract characters except of K string
    Sometimes, while working with Python strings, we can have a problem in which we require to extract all the elements of string except those which present in a substring. This is quite common problem and has application in many domains including those of day-day and competitive programming. Lets discu
    6 min read
  • Python | Lowercase first character of String
    The problem of capitalizing a string is quite common and has been discussed many times. But sometimes, we might have a problem like this in which we need to convert the first character of the string to lowercase. Let us discuss certain ways in which this can be performed. Method #1: Using string sli
    4 min read
  • Python - Replace occurrences by K except first character
    Given a String, the task is to write a Python program to replace occurrences by K of character at 1st index, except at 1st index. Examples: Input : test_str = 'geeksforgeeksforgeeks', K = '@' Output : geeksfor@eeksfor@eeks Explanation : All occurrences of g are converted to @ except 0th index. Input
    5 min read
  • Python - Lowercase Kth Character in string
    The problem of lowercasing a string is quite common and has been discussed many times. But sometimes, we might have a problem like this in which we need to convert the Nth character of string to lowercase. Let’s discuss certain ways in which this can be performed. Method #1 : Using string slicing +
    4 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