Python | Substitute character with its occurrence
Last Updated :
22 Mar, 2023
Sometimes, while working with Python, we can have a problem in which we need to substitute a character with its occurrence in a string. This a peculiar problem but can have application in many domains. Lets discuss certain ways in which this task can be performed.
Method #1 : Using loop This is brute way to solve the problem. In this, we run a loop for each character in string and perform the substitution while increasing the counter each time.
Python3
test_str = "geeksforgeeks is best for geeks"
print ( "The original string is : " + test_str)
test_let = 'g'
res = ''
count = 1
for chr in test_str:
if chr = = test_let:
res + = str (count)
count + = 1
else :
res + = chr
print ( "The string after performing substitution : " + str (res))
|
Output :
The original string is : geeksforgeeks is best for geeks
The string after performing substitution : 1eeksfor2eeks is best for 3eeks
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 #2: Using lambda + regex + next() The combination of above functions can be used to perform this task. In this we perform the task of iteration using lambda, the regex and next() is used to perform the task of count iteration and finding the target char.
Python3
from itertools import count
import re
test_str = "geeksforgeeks is best for geeks"
print ( "The original string is : " + test_str)
test_let = 'g'
cnt = count( 1 )
res = re.sub(r "g" , lambda x: "{}" . format ( next (cnt)), test_str)
print ( "The string after performing substitution : " + str (res))
|
Output :
The original string is : geeksforgeeks is best for geeks
The string after performing substitution : 1eeksfor2eeks is best for 3eeks
Time complexity: O(n), where n is the length of the input string.
Auxiliary space: O(1), since the space used by the count iterator and the lambda function is constant and does not depend on the size of the input.
Method #3: Using count() method and slicing
Python3
test_str = "geeksforgeeks is best for geeks"
print ( "The original string is : " + test_str)
test_let = 'g'
res = ''
for i in range ( 0 , len (test_str)):
if (test_str[i] = = test_let):
res + = str (test_str[:i].count(test_let) + 1 )
else :
res + = test_str[i]
print ( "The string after performing substitution : " + str (res))
|
Output
The original string is : geeksforgeeks is best for geeks
The string after performing substitution : 1eeksfor2eeks is best for 3eeks
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #4: Using Replace() Method
Python3
test_str = "geeksforgeeks is best for geeks"
print ( "The original string is : " + test_str)
test_let = 'g'
count = 1
for i in range (test_str.count(test_let)):
test_str = test_str.replace(test_let, str (count), 1 )
count + = 1
print ( "The string after performing substitution : " + str (test_str))
|
Output
The original string is : geeksforgeeks is best for geeks
The string after performing substitution : 1eeksfor2eeks is best for 3eeks
Time Complexity: O(n^2)
Auxiliary Space: O(n)
Method #5: Using operator.countOf() method and slicing
- Initiated a for loop to traverse the list
- Used operator.countOf() and slicing to replace the given character with its occurence and concatenate to res
- Display res
Python3
test_str = "geeksforgeeks is best for geeks"
print ( "The original string is : " + test_str)
test_let = 'g'
res = ''
import operator
for i in range ( 0 , len (test_str)):
if (test_str[i] = = test_let):
res + = str (operator.countOf(test_str[:i],test_let) + 1 )
else :
res + = test_str[i]
print ( "The string after performing substitution : " + str (res))
|
Output
The original string is : geeksforgeeks is best for geeks
The string after performing substitution : 1eeksfor2eeks is best for 3eeks
Time Complexity : O(N)
Auxiliary Space : O(1)
Method #6: Using list comprehension and join() method
Here’s an alternative method that uses a list comprehension to iterate through each character in the string and replace the specified character with its occurrence. The join() method is used to join the characters back together to form the final string.
- The list comprehension iterates through each character in the string using the enumerate() function to access both the index and the character.
- If the character is equal to the specified letter (test_let), the expression str(test_str[:i].count(test_let) + 1) is evaluated. This counts the number of occurrences of the letter in the substring up to the current index (using string slicing) and adds 1 to get the total number of occurrences, then converts the result to a string. Otherwise, the original character is used.
- The join() method is used to join the resulting list of characters back together into a string.
Python3
test_str = "geeksforgeeks is best for geeks"
print ( "The original string is : " + test_str)
test_let = 'g'
res = ''.join([ str (test_str[:i].count(test_let) + 1 ) if char = = test_let else char for i, char in enumerate (test_str)])
print ( "The string after performing substitution : " + str (res))
|
Output
The original string is : geeksforgeeks is best for geeks
The string after performing substitution : 1eeksfor2eeks is best for 3eeks
Time Complexity: O(n)
Auxiliary Space: O(n)
Similar Reads
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 | 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 - Successive Characters Frequency
Sometimes, while working with Python strings, we can have a problem in which we need to find the frequency of next character of a particular word in string. This is quite unique problem and has the potential for application in day-day programming and web development. Let's discuss certain ways in wh
6 min read
Python - Filter Tuples with Strings of specific characters
Given a Tuple List, extract tuples, which have strings made up of certain characters. Input : test_list = [('gfg', 'best'), ('gfg', 'good'), ('fest', 'gfg')], char_str = 'gfestb' Output : [('gfg', 'best'), ('fest', 'gfg')] Explanation : All tuples contain characters from char_str. Input : test_list
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 | Get the string after occurrence of given substring
The problem involves getting the string that is occurring after the substring has been found. Let's discuss certain ways in which this task can be performed using Python. Using partition()To extract the portion of a string that occurs after a specific substring partition() method is an efficient and
3 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
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 - 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 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