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 Different Characters in String at Once
Next article icon

Python | Replace multiple occurrence of character by single

Last Updated : 31 Jul, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 : Win

Replace multiple occurrence of character by single

Approach #1 : Naive Approach This method is a brute force approach in which we take another list ‘new_str’. Use a for loop to check if the given character is repeated or not. If repeated multiple times, append the character single time to the list. Other characters(Not the given character) are simply appended to the list without any alteration. 

Python3




# Python program to replace multiple
# occurrences of a character by a single character
 
def replace(s, ch):
    new_str = []
    l = len(s)
     
    for i in range(len(s)):
        if (s[i] == ch and i != (l-1) and
           i != 0 and s[i + 1] != ch and s[i-1] != ch):
            new_str.append(s[i])
             
        elif s[i] == ch:
            if ((i != (l-1) and s[i + 1] == ch) and
               (i != 0 and s[i-1] != ch)):
                new_str.append(s[i])
                 
        else:
            new_str.append(s[i])
         
    return ("".join(i for i in new_str))
 
 
# Driver code
s = 'Geeksforgeeks'
char = 'e'
print(replace(s, char))
 
 
Output
Geksforgeks 

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

Approach #2 : Using Python Regex 

Python3




import re
 
# Function to replace multiple occurrences 
# of a character by a single character
def replace(string, char):
    pattern = char + '{2,}'
    string = re.sub(pattern, char, string)
    return string
 
# Driver code
string = 'Geeksforgeeks'
char = 'e'
print(replace(string, char))
 
 
Output
Geksforgeks 

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

Approach 3: Using itertools.groupby 

In this approach, we use the groupby function to group consecutive characters in the string. We then iterate over the groups and check if the current group consists of the given character. If so, we add only one occurrence of that character to the new string. Otherwise, we add all the characters in the group to the new string. Finally, we return the new string with consecutive occurrences of the given character replaced by a single occurrence.

Python3




from itertools import groupby
 
def replace_multiple_occurrence(string, ch):
    groups = groupby(string)
    new_str = ""
    for key, group in groups:
        if key == ch:
            new_str += ch
        else:
            new_str += ''.join(group)
    return new_str
string = 'Geeksforgeeks'
ch = 'e'
print(replace_multiple_occurrence(string, ch))
 
 
Output
Geksforgeks 

Time complexity: O(n + m*k), The groupby function from the itertools module has a time complexity of O(n), where n is the length of the input string. The for loop that iterates over the groups has a time complexity of O(m), where m is the number of groups in the input string. For each group, we need to iterate over the iterator of consecutive characters, which has a time complexity of O(k), where k is the number of consecutive occurrences of the character in that group.

Auxiliary Space: O(n), The space complexity of the groupby function is O(1), as it does not create any new data structures. The space complexity of the new string new_str is O(n), as it stores the entire input string. The space complexity of the for loop is O(1), as it only uses a constant amount of additional memory for variables

Approach 4: Using the split and join methods

Step-by-step algorithm:

  1. Split the given string by the given character.
  2. Remove any empty strings resulting from the split operation.
  3. Join the remaining strings with the given character.
  4. Return the resulting string.

Python3




def replace(string, char):
    return char.join([s for s in string.split(char) if s != ''])
 
# Driver code
string = 'Geeksforgeeks'
char = 'e'
print(replace(string, char))
 
 
Output
Geksforgeks 

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



Next Article
Python - Replace Different Characters in String at Once

S

Smitha Dinesh Semwal
Improve
Article Tags :
  • Python
  • Python Programs
  • Python Regex-programs
  • python-regex
Practice Tags :
  • python

Similar Reads

  • 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 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 | 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 - 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
  • 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 - 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
  • 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
  • Remove Multiple Characters from a String in Python
    Removing multiple characters from a string in Python can be achieved using various methods, such as str.replace(), regular expressions, or list comprehensions. Each method serves a specific use case, and the choice depends on your requirements. Let’s explore the different ways to achieve this in det
    3 min read
  • Multiple Indices Replace in String - Python
    In this problem, we have to replace the characters in a string at multiple specified indices and the following methods demonstrate how to perform this operation efficiently: Using loop and join()join() is a brute force method where we first convert the string into a list then we iterate through the
    3 min read
  • Python Program to Replace all Occurrences of ‘a’ with $ in a String
    Given a string, the task is to write a Python program to replace all occurrence of 'a' with $. Examples: Input: Ali has all aces Output: $li h$s $ll $ces Input: All Exams are over Output: $ll Ex$ms $re Over Method 1: uses splitting of the given specified string into a set of characters. An empty str
    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