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 stringtest_str = "geeksforgeeks is best for all geeks" # printing original stringprint("The original string is : " + str(test_str)) # initializing KK = '$' # initializing NN = 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 resultprint("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 stringtest_str = "geeksforgeeks is best for all geeks" # printing original stringprint("The original string is : " + str(test_str)) # initializing KK = '$' # initializing NN = 5 res = ''.join(ele if idx % N or idx == 0 else K for idx, ele in enumerate(test_str)) # printing resultprint("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


 (2).jpg)
