Open In App

Python program to replace every Nth character in String

Improve
Improve
Like Article
Like
Save
Share
Report

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

The time complexity of the given code is O(N), where N is the length of the input string “test_str”. 

The auxiliary space used by the code is also O(N), where N is the length of the input string “test_str”.

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))


Output

The original string is : geeksforgeeks is best for all geeks
String after replacement : geeks$orge$ks i$ bes$ for$all $eeks

The time complexity of this code is O(n), where n is the length of the input string test_str.

The auxiliary space used by the code is also O(n), where n is the length of the input string. 

Method 4:Using string concatenation

  1. Initialize a string ‘test_str’ with the value “geeksforgeeks is best for all geeks”.
  2. Print the original string.
  3. Initialize a character ‘K’ with the value ‘$’.
  4. Initialize an integer ‘N’ with the value 5.
  5. Create an empty string ‘new_str’ to store the modified string.
  6. Loop through each character of the string ‘test_str’ using the ‘range()’ function and ‘len()’ function.
  7. Check if the current index is a multiple of N using the modulo operator ‘%’.
  8. If the index is a multiple of N, add the character K to the new string ‘new_str’.
  9. If the index is not a multiple of N, add the original character from ‘test_str’ to the new string ‘new_str’.
  10. Print the final modified string ‘new_str’.

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
 
# create a new empty string to store the modified string
new_str = ""
 
# loop through the characters in the original string
for i in range(len(test_str)):
    # check if the current index is a multiple of N
    if (i+1) % N == 0:
        # add the replacement character K to the new string
        new_str += K
    else:
        # add the original character to the new string
        new_str += test_str[i]
 
# printing result
print("String after replacement : " + str(new_str))
#This code is contributed by Vinay Pinjala.


Output

The original string is : geeksforgeeks is best for all geeks
String after replacement : geek$forg$eks $s be$t fo$ all$geek$

The time complexity of the algorithm is O(N), where N is the length of the string ‘test_str’. This is because we are looping through each character of the string once.

The space complexity of the algorithm is also O(N), where N is the length of the string ‘test_str’. This is because we are creating a new string ‘new_str’ to store the modified string, which will have the same length as the original string in the worst case.



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