Python | Replace characters after K occurrences
Last Updated : 18 May, 2023
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
test_str = "geeksforgeeks is best for geeks" print ( "The original string is : " + test_str) K = 2 repl_char = "*" 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 :] 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
test_str = "geeksforgeeks is best for geeks" print ( "The original string is : " + test_str) K = 2 repl_char = "*" res = "".join( chr if test_str.count( chr , 0 , idx) < K else repl_char for idx, chr in enumerate (test_str)) 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:
- Create a list of characters using a list comprehension, where each character is replaced with repl_char if its count.
- 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.
- Finally, the list is joined back into a string using the join method.
Python3
test_str = "geeksforgeeks is best for geeks" K = 2 repl_char = "*" chars =
res = "".join(chars) 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:
- 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. - 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.
- Increment the counter for the current character.
- Convert the list back to a string using the join() method.
- Print the modified string.
Python3
test_str = "geeksforgeeks is best for geeks" print ( "The original string is : " + test_str) K = 2 repl_char = "*" 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) 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
test_str = "geeksforgeeks is best for geeks" print ( "The original string is: " + test_str) K = 2 repl_char = "*" 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 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.
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