Python program to replace every Nth character in String
Given a string, the task is to write a Python program to replace every Nth character in a string by the given value K.
Examples:
Input : test_str = “geeksforgeeks is best for all geeks”, K = ‘$’, N = 5
Output : geeks$orge$ks i$ bes$ for$all $eeks
Explanation : Every 5th character is converted to $.
Input : test_str = “geeksforgeeks is best for all geeks”, K = ‘*’, N = 5
Output : geeks*orge*ks i* bes* for*all *eeks
Explanation : Every 5th occurrence is converted to *.
Method 1 : Using loop and enumerate()
In this, we perform an iteration of each character and check if its Nth by performing modulo, i.e finding remainder by N. If its Nth occurrence, the character is replaced by K.
Example
Python3
# initializing string test_str = "geeksforgeeks is best for all geeks" # printing original string print ( "The original string is : " + str (test_str)) # initializing K K = '$' # initializing N N = 5 res = '' for idx, ele in enumerate (test_str): # add K if idx is multiple of N if idx % N = = 0 and idx ! = 0 : res = res + K else : res = res + ele # printing result print ( "String after replacement : " + str (res)) |
Output:
The original string is : geeksforgeeks is best for all geeks
String after replacement : geeks$orge$ks i$ bes$ for$all $eeks
Method 2 : Using generator expression, join() and enumerate()
In this, the construction of string happens using join(). The enumerate(), helps to get required indices. The generator expression provides a shorthand approach to this problem.
Example
Python3
# initializing string test_str = "geeksforgeeks is best for all geeks" # printing original string print ( "The original string is : " + str (test_str)) # initializing K K = '$' # initializing N N = 5 res = ''.join(ele if idx % N or idx = = 0 else K for idx, ele in enumerate (test_str)) # printing result print ( "String after replacement : " + str (res)) |
Output:
The original string is : geeksforgeeks is best for all geeks
String after replacement : geeks$orge$ks i$ bes$ for$all $eeks
The time and space complexity of all the methods are the same:
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 3 : Using lists
Python3
# initializing string test_str = "geeksforgeeks is best for all geeks" # printing original string print ( "The original string is : " + str (test_str)) # initializing K K = '$' # initializing N N = 5 x = list (test_str) ns = "" for i in range ( 0 , len (x)): if (i! = 0 and i % 5 = = 0 ): ns + = K else : ns + = test_str[i] # printing result print ( "String after replacement : " + str (ns)) |
The original string is : geeksforgeeks is best for all geeks String after replacement : geeks$orge$ks i$ bes$ for$all $eeks
Please Login to comment...