Open In App

Python | Substitute character with its occurrence

Improve
Improve
Like Article
Like
Save
Share
Report

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




# Python3 code to demonstrate working of
# Substitute character with its occurrence
# Using loop
 
# initializing string
test_str = "geeksforgeeks is best for geeks"
 
# printing original string
print("The original string is : " + test_str)
 
# initializing letter
test_let = 'g'
 
# Substitute character with its occurrence
# Using loop
res = ''
count = 1
for chr in test_str:
    if chr == test_let:
        res += str(count)
        count += 1
    else:
        res += chr
 
# printing result
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




# Python3 code to demonstrate working of
# Substitute character with its occurrence
# Using lambda + regex + next()
from itertools import count
import re
 
# initializing string
test_str = "geeksforgeeks is best for geeks"
 
# printing original string
print("The original string is : " + test_str)
 
# initializing letter
test_let = 'g'
 
# Substitute character with its occurrence
# Using lambda + regex + next()
cnt = count(1)
res = re.sub(r"g", lambda x: "{}".format(next(cnt)), test_str)
 
# printing result
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




# Python3 code to demonstrate working of
# Substitute character with its occurrence
 
# initializing string
test_str = "geeksforgeeks is best for geeks"
 
# printing original string
print("The original string is : " + test_str)
 
# initializing letter
test_let = 'g'
 
# Substitute character with its occurrence
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]
 
# printing result
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




#Python3 code to demonstrate working of
#Substitute character with its occurrence
#Using Replace() Method
#initializing string
test_str = "geeksforgeeks is best for geeks"
 
#printing original string
print("The original string is : " + test_str)
 
#initializing letter
test_let = 'g'
 
#Substitute character with its occurrence
count = 1
for i in range(test_str.count(test_let)):
  test_str = test_str.replace(test_let, str(count), 1)
  count += 1
 
#printing result
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

  1. Initiated a for loop to traverse the list
  2. Used operator.countOf() and slicing to replace the given character with its occurence and concatenate to res
  3. Display res

Python3




# Python3 code to demonstrate working of
# Substitute character with its occurrence
 
# initializing string
test_str = "geeksforgeeks is best for geeks"
 
# printing original string
print("The original string is : " + test_str)
 
# initializing letter
test_let = 'g'
 
# Substitute character with its occurrence
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]
 
# printing result
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




# Python3 code to demonstrate working of
# Substitute character with its occurrence
 
# initializing string
test_str = "geeksforgeeks is best for geeks"
 
# printing original string
print("The original string is : " + test_str)
 
# initializing letter
test_let = 'g'
 
# Substitute character with its occurrence
res = ''.join([str(test_str[:i].count(test_let) + 1) if char == test_let else char for i, char in enumerate(test_str)])
 
# printing result
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)



Last Updated : 22 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads