Open In App

Python | Multiple indices Replace in String

Last Updated : 16 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python Stings, we can have a problem, in which we need to perform the replace of characters based on several indices of String. This kind of problem can have applications in many domains. Lets discuss certain ways in which this task can be performed.

Method #1 : Using loop + join() This is brute force way in which this task can be performed. In this, we iterate for each character and substitute with replace character if that is one. 

Python3




# Python3 code to demonstrate working of
# Multiple indices Replace in String
# Using loop + join()
 
# initializing string
test_str = 'geeksforgeeks is best'
 
# printing original string
print("The original string is : " + test_str)
 
# initializing list
test_list = [2, 4, 7, 10]
 
# initializing repl char
repl_char = '*'
 
# Multiple indices Replace in String
# Using loop + join()
temp = list(test_str)
for idx in test_list:
    temp[idx] = repl_char
res = ''.join(temp)
 
# printing result
print("The String after performing replace : " + str(res))


Output : 

The original string is : geeksforgeeks is best
The String after performing replace : ge*k*fo*ge*ks is best

  Method #2 : Using list comprehension + join() The combination of above functions can also be used to perform this task. In this, we perform similar task as above, just in one liner format using list comprehension. 

Python3




# Python3 code to demonstrate working of
# Multiple indices Replace in String
# Using list comprehension + join()
 
# initializing string
test_str = 'geeksforgeeks is best'
 
# printing original string
print("The original string is : " + test_str)
 
# initializing list
test_list = [2, 4, 7, 10]
 
# initializing repl char
repl_char = '*'
 
# Multiple indices Replace in String
# Using list comprehension + join()
temp = list(test_str)
res = [repl_char if idx in test_list else ele for idx, ele in enumerate(temp)]
res = ''.join(res)
 
# printing result
print("The String after performing replace : " + str(res))


Output : 

The original string is : geeksforgeeks is best
The String after performing replace : ge*k*fo*ge*ks is best

The Time and Space Complexity for all the methods are the same:

Time Complexity: O(n)

Space Complexity: O(n)

Method #3:  Using map() + join() + enumerate() methods and lambda to replace characters in string

Step by step Algorithm:

  1. Initialize input string, list of indices to replace, and replacement character.
  2. Use the enumerate() function to get a tuple of index and character for each character in the input string.
  3. Use the map() function to iterate over each tuple and apply the lambda function.
  4. In the lambda function, check if the index of the character is in the list of indices to replace. If yes, replace the character with the replacement character. If no, keep the character as is.
  5. Join the resulting characters using the join() function to get the final string.
  6. Return the final string.

Python3




test_str = 'geeksforgeeks is best'
test_list = [2, 4, 7, 10]
repl_char = '*'
res = ''.join(map(lambda x: repl_char if x[0] in test_list else x[1], enumerate(test_str)))
print("The String after performing replace : " + str(res))


Output

The String after performing replace : ge*k*fo*ge*ks is best

Time complexity: O(n), where n is the length of the input string.
Auxiliary Space: O(n), where n is the length of the input string. This is because we are creating a new string object to store the final result.

Method #4: Using replace() method inside a loop

Step-by-step explanation:

  • Initialize the string test_str, the list test_list, and the replacement character repl_char.
  • Print the original string.
  • Loop through the elements of test_list.
  • For each element i in test_list, we replace the character at the i-th position in test_str with repl_char. We achieve this by slicing the string into two parts: the part before the i-th character, and the part after the i-th character then concatenate the repl_char between these two parts.
  • We print the resulting string.

Python3




# initializing string
test_str = 'geeksforgeeks is best'
 
# printing original string
print("The original string is : " + test_str)
 
# initializing list
test_list = [2, 4, 7, 10]
 
# initializing repl char
repl_char = '*'
 
# Multiple indices Replace in String
# Using replace() inside a loop
for i in test_list:
    test_str = test_str[:i] + repl_char + test_str[i+1:]
 
# printing result
print("The String after performing replace : " + str(test_str))


Output

The original string is : geeksforgeeks is best
The String after performing replace : ge*k*fo*ge*ks is best

Time complexity: O(n*m), where n is the length of the string and m is the length of the list.
Auxiliary space: O(n), where n is the length of the string. This is because we are modifying the original string in-place, and not creating any new data structures.



Similar Reads

replace() in Python to replace a substring
Given a string str that may contain one more occurrences of “AB”. Replace all occurrences of “AB” with “C” in str. Examples: Input : str = "helloABworld" Output : str = "helloCworld" Input : str = "fghABsdfABysu" Output : str = "fghCsdfCysu" This problem has existing solution please refer Replace all occurrences of string AB with C without using ex
1 min read
Python | Pandas Series.str.replace() to replace text in a series
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages that makes importing and analyzing data much easier. Pandas Series.str.replace() method works like Python .replace() method only, but it works on Series too. Before calling .replace() on a Panda
5 min read
NumPy indices() Method | Create Array of Indices
The indices() method returns an array representing the indices of a grid. It computes an array where the subarrays contain index values 0, 1, … varying only along the corresponding axis. Example C/C++ Code import numpy as np gfg = np.indices((2, 3)) print (gfg) Output : [[[0 0 0] [1 1 1]] [[0 1 2] [0 1 2]]]Syntax numpy.indices(dimensions, dtype, sp
2 min read
Python | Replace multiple occurrence of character by single
Given a string and a character, write a Python program to replace multiple occurrences of the given character by a single character. Examples: Input : Geeksforgeeks, ch = 'e' Output : Geksforgeks Input : Wiiiin, ch = 'i' Output : WinReplace multiple occurrence of character by singleApproach #1 : Naive Approach This method is a brute force approach
4 min read
Python | Replace multiple characters at once
The replacement of one character with another is a common problem that every Python programmer would have worked with in the past. But sometimes, we require a simple one-line solution that can perform this particular task. Let's discuss certain ways in which this task can be performed. Method 1: Replace multiple characters using nested replace() Th
6 min read
Python - Replace multiple words with K
Sometimes, while working with Python strings, we can have a problem in which we need to perform a replace of multiple words with a single word. This can have application in many domains including day-day programming and school programming. Lets discuss certain ways in which this task can be performed. Method #1 : Using join() + split() + list compr
7 min read
Replace Multiple Lines From A File Using Python
In Python, replacing multiple lines in a file consists of updating specific contents within a text file. This can be done using various modules and their associated functions. In this article, we will explore three different approaches along with the practical implementation of each approach in terms of example code and output. Replace Multiple Lin
3 min read
Python - Replace K with Multiple values
Sometimes, while working with Python Strings, we can have a problem in which we need to perform replace of single character/work with particular list of values, based on occurrence. This kind of problem can have application in school and day-day programming. Let's discuss certain ways in which this task can be performed. Input : test_str = '* is *
5 min read
Pandas Replace Multiple Values in Python
Replacing multiple values in a Pandas DataFrame or Series is a common operation in data manipulation tasks. Pandas provides several versatile methods for achieving this, allowing you to seamlessly replace specific values with desired alternatives. In this context, we will explore various approaches to replace multiple values in Python using Pandas.
3 min read
Python | Vowel indices in String
Sometimes, while working with Python Strings, we can have a problem in which we need to extract indices of vowels in it. This kind of application is common in day-day programming. Lets discuss certain ways in which this task can be performed. Method #1 : Using loop This is one way in which this task can be performed. In this we use brute force to p
6 min read
Practice Tags :