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:
Python - Replace occurrences by K except first character
Next article icon

Python | Replace characters after K occurrences

Last Updated : 18 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 brute force way in which this problem can be solved. In this, we run a loop on a string and keep track of occurrences and perform replace when above K occurrence. 

Python3




# Python3 code to demonstrate working of
# Replace characters after K occurrences
# Using loop + string slices
 
# initializing string
test_str = "geeksforgeeks is best for geeks"
 
# printing original string
print("The original string is : " + test_str)
 
# initializing K
K = 2
 
# initializing Repl char
repl_char = "*"
 
# Replace characters after K occurrences
# Using loop + string slices
for sub in set(test_str):
    for idx in [idx for idx in range(len(test_str)) if test_str[idx] == sub][K:]:
        test_str = test_str[:idx] + repl_char + test_str[idx + 1:]
 
# printing result
print("The string after performing replace : " + test_str)
 
 
Output : 
The original string is : geeksforgeeks is best for geeks The string after performing replace : geeksforg**ks i* b**t*for******

Time Complexity: O(n2), where n is the length of the string.
Auxiliary Space: O(n), where n is the length of the string.

Method #2 : Using join() + count() + enumerate() 

This is the shorthand by which this task can be performed. In this, we employ count() to check for the count of strings and join() and enumerate() can be used to perform the task of new string construction. 

Python3




# Python3 code to demonstrate working of
# Replace characters after K occurrences
# Using join() + count() + enumerate()
 
# initializing string
test_str = "geeksforgeeks is best for geeks"
 
# printing original string
print("The original string is : " + test_str)
 
# initializing K
K = 2
 
# initializing Repl char
repl_char = "*"
 
# Replace characters after K occurrences
# Using join() + count() + enumerate()
res = "".join(chr if test_str.count(chr, 0, idx) < K
              else repl_char for idx, chr in enumerate(test_str))
 
# printing result
print("The string after performing replace : " + res)
 
 
Output : 
The original string is : geeksforgeeks is best for geeks The string after performing replace : geeksforg**ks i* b**t*for******

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

Method 3: Using list comprehension:

  1. Create a list of characters using a list comprehension, where each character is replaced with repl_char if its count.
  2. The first ‘i’th characters of the string are greater than or equal to K. The enumerate function is used to get the index i of each character. 
  3. Finally, the list is joined back into a string using the join method.

Python3




# Initialzing list and value
test_str = "geeksforgeeks is best for geeks"
K = 2
 
repl_char = "*"
 
chars =
res = "".join(chars)
 
# Printing the result
print("The string after performing replace : " + res)
 
 
Output
The string after performing replace : geeksforg**ks i* b**t*for******

Time complexity: O(n^2), where n is the length of the input string, because test_str.count is called n times, each time with a string of length up to n. The Auxiliary space: O(n), because a new list of length n is created

Method  4: Using list and slicing

Approach:

  1. Convert the input string test_str to a list of characters using the list() method.
    Initialize a counter variable to keep track of the number of occurrences of each character in the input string.
  2. Loop through each character in the list.
    • If the number of occurrences of the current character is less than K, then do nothing.
    • If the number of occurrences of the current character is equal to K, then replace all subsequent occurrences of the current character with the replacement character repl_char.
    • If the number of occurrences of the current character is greater than K, then replace the current occurrence of the character with the replacement character repl_char.
  3. Increment the counter for the current character.
  4. Convert the list back to a string using the join() method.
  5. Print the modified string.

Python3




# initializing string
test_str = "geeksforgeeks is best for geeks"
 
# printing original string
print("The original string is : " + test_str)
 
# initializing K
K = 2
 
# initializing Repl char
repl_char = "*"
 
# Replace characters after K occurrences
# Using list and slicing
lst = list(test_str)
counter = {}
for i, char in enumerate(lst):
    if char not in counter:
        counter[char] = 0
    if counter[char] == K:
        for j in range(i, len(lst)):
            if lst[j] == char:
                lst[j] = repl_char
    elif counter[char] > K:
        lst[i] = repl_char
    counter[char] += 1
res = ''.join(lst)
 
# printing result
print("The string after performing replace : " + res)
 
 
Output
The original string is : geeksforgeeks is best for geeks The string after performing replace : geeksforg**ks i* b**t*for******

Time complexity: O(n^2), where n is the length of the input string. 
Auxiliary space: O(k), where k is the number of unique characters in the input string. 

Method 5: Using a dictionary

Python3




# Initializing string
test_str = "geeksforgeeks is best for geeks"
 
# Printing original string
print("The original string is: " + test_str)
 
# Initializing K
K = 2
 
# initializing Repl char
repl_char = "*"
 
# Replace characters after K occurrences
# using a dictionary
counter = {}
 
res = ""
 
for char in test_str:
    if char not in counter:
        counter[char] = 1
    else:
        counter[char] += 1
    if counter[char] <= K:
        res += char
    else:
        res += repl_char
 
# Printing result
print("The string after performing replace: " + res)
 
 
Output
The original string is: geeksforgeeks is best for geeks The string after performing replace: geeksforg**ks i* b**t*for******

Time Complexity: O(n), where n is the length of the input string. It iterates through the string once and performs constant-time operations for each character.
Auxiliary Space: O(n), where n is the length of the input string.



Next Article
Python - Replace occurrences by K except first character
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python string-programs
Practice Tags :
  • python

Similar Reads

  • 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 - Remove N characters after K
    Given a String, remove N characters after K character. Input : test_str = 'ge@987eksfor@123geeks is best@212 for cs', N = 3, K = '@' Output : 'geeksforgeeks is best for cs' Explanation : All 3 required occurrences removed. Input : test_str = 'geeksfor@123geeks is best for cs', N = 3, K = '@' Output
    2 min read
  • Python - Replace multiple characters at once
    Replacing multiple characters in a string is a common task in Python Below, we explore methods to replace multiple characters at once, ranked from the most efficient to the least. Using translate() with maketrans() translate() method combined with maketrans() is the most efficient way to replace mul
    2 min read
  • Python | Replace multiple occurrence of character by single
    Given a string and a character, write a Python program to replace multiple occurrences of the given character by a single character. Examples: Input : Geeksforgeeks, ch = 'e' Output : Geksforgeks Input : Wiiiin, ch = 'i' Output : WinReplace multiple occurrence of character by singleApproach #1 : Nai
    4 min read
  • Python - Extract String after Nth occurrence of K character
    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"
    7 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
  • Python - Replace Different Characters in String at Once
    The task is to replace multiple different characters in a string simultaneously based on a given mapping. For example, given the string: s = "hello world" and replacements = {'h': 'H', 'o': '0', 'd': 'D'} after replacing the specified characters, the result will be: "Hell0 w0rlD" Using str.translate
    3 min read
  • Python - Non-Overlapping occurrences of N Repeated K character
    Given a String, compute non-overlapping occurrences of N repeated K character. Input : test_str = 'aaabaaaabbaa', K = "a", N = 3 Output : 2 Explanation : "aaa" occurs twice as non-overlapping run. Input : test_str = 'aaabaaaabbbaa', K = "b", N = 3 Output : 1 Explanation : "bbb" occurs once as non-ov
    6 min read
  • Python - Replace duplicate Occurrence in String
    Sometimes, while working with Python strings, we can have problem in which we need to perform the replace of a word. This is quite common task and has been discussed many times. But sometimes, the requirement is to replace occurrence of only duplicate, i.e from second occurrence. This has applicatio
    6 min read
  • 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
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