Python | Replace multiple characters at once
Last Updated :
08 May, 2023
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()
This problem can be solved using the nested replace method, which internally would create a temp. variable to hold the intermediate replacement state.
Python3
test_str = "abbabba"
print ( "The original string is : " + str (test_str))
res = test_str.replace( 'a' , '%temp%' ).replace( 'b' , 'a' ).replace( '%temp%' , 'b' )
print ( "The string after replacement of positions : " + res)
|
Output:
The original string is : abbabba
The string after replacement of positions : baabaab
Time Complexity: O(n)
Auxiliary Space: O(1)
Method 2: Replace multiple characters using translate() + maketrans()
There is also a dedication function that can perform this type of replacement task in a single line hence this is a recommended way to solve this particular problem. Works only in Python2.
Python3
import string
test_str = "abbabba"
print ( "The original string is : " + str (test_str))
res = test_str.translate(string.maketrans( "ab" , "ba" ))
print ( "The string after replacement of positions : " + res)
|
Output:
The original string is : abbabba
The string after replacement of positions : baabaab
Time complexity: O(n), where n is the length of the input string.
This is because the translate() method takes O(n) time to replace each character in the string.
Auxiliary space: O(1), as the space used by the program does not increase with the size of the input string. The method maketrans() and the variables used to store the input and output strings take constant space.
Method 3: Replace multiple characters using re.subn()
subn() is similar to sub() in all ways, except in its way of providing output. It returns a tuple with a count of the total of replacement and the new string rather than just the string.
Python3
import re
test_str = "34a7bb86abba032"
print ( "The original string is : " + str (test_str))
res, n = re.subn( '[0-9]' , '', test_str)
print ( "The string after replacement of positions : " + res)
|
Output:
The original string is : 34a7bb86abba032
The string after replacement of positions : abbabba
Time complexity: O(n), where n is the length of string test_str.
Auxiliary space: O(n), where n is the length of res string.
Method 4: Using List comprehension:
1.Define the input string test_str.
2.Create a new string new_str by iterating over each character in test_str.
3.If the character is ‘a’, replace it with ‘b’.
4.If the character is ‘b’, replace it with ‘a’.
5.If the character is anything else, leave it unchanged.
6.Concatenate the modified character to new_str.
7.Print new_str.
Python3
test_str = "abbabba"
print ( "The original string is : " + str (test_str))
new_str = ' '.join([' a ' if char == ' b ' else ' b ' if char == ' a' else char for char in test_str])
print ( "The string after replacement of positions : " + new_str)
|
Output
The original string is : abbabba
The string after replacement of positions : baabaab
Time complexity: O(n), where n is the length of the input string test_str. This is because we need to iterate over each character in the string exactly once.
Auxiliary space: O(n), because we create a new string new_str that is the same length as the input string.
Method #5: Using a dictionary to map characters to their replacements
Step-by-step approach:
- Initialize a dictionary where the keys are the characters to be replaced, and the values are their replacements.
- Loop through the string and replace each character with its corresponding value from the dictionary.
- Join the list of replaced characters into a string.
Below is the implementation of the above approach:
Python3
test_str = "abbabba"
print ( "The original string is : " + str (test_str))
replacements = { 'a' : 'b' , 'b' : 'a' }
replaced_chars = [replacements.get(char, char) for char in test_str]
res = ''.join(replaced_chars)
print ( "The string after replacement of positions : " + res)
|
Output
The original string is : abbabba
The string after replacement of positions : baabaab
Time complexity: O(n), where n is the length of the string. This is because we loop through the string once.
Auxiliary space: O(n), where n is the length of the string. This is because we create a list of replaced characters before joining them into a string.
Method 6: using a regular expression with the re.sub() method.
Initialize the original string test_str.
Define a dictionary replacements that maps the characters to their replacements.
Create a regular expression pattern using the | operator to match any of the keys in the replacements dictionary.
Use the re.sub() method to replace any match of the pattern in the test_str string with its corresponding value from the replacements dictionary.
Assign the result to the res variable.
Print the final result.
Python3
import re
test_str = "abbabba"
print ( "The original string is : " + str (test_str))
replacements = { 'a' : 'b' , 'b' : 'a' }
pattern = '|' .join(replacements.keys())
res = re.sub(pattern, lambda match: replacements[match.group( 0 )], test_str)
print ( "The string after replacement of positions : " + res)
|
Output
The original string is : abbabba
The string after replacement of positions : baabaab
Time complexity of this method is O(n), where n is the length of the input string.
Auxiliary space complexity is O(k), where k is the number of unique characters in the replacements dictionary.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...