Python | Replace multiple occurrence of character by single
Last Updated : 31 Jul, 2023
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
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)) s = 'Geeksforgeeks' char = 'e' print (replace(s, char)) |
Time Complexity: O(N)
Auxiliary Space: O(N)
Approach #2 : Using Python Regex
Python3
import re def replace(string, char): pattern = char + '{2,}' string = re.sub(pattern, char, string) return string string = 'Geeksforgeeks' char = 'e' print (replace(string, char)) |
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)) |
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:
- Split the given string by the given character.
- Remove any empty strings resulting from the split operation.
- Join the remaining strings with the given character.
- Return the resulting string.
Python3
def replace(string, char): return char.join([s for s in string.split(char) if s ! = '']) string = 'Geeksforgeeks' char = 'e' print (replace(string, char)) |
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.
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