Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python program to replace every Nth character in String

  • Last Updated : 21 Apr, 2021

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:

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

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




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!