Open In App
Related Articles

Python | Replace multiple characters at once

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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

# initializing string
test_str = "abbabba"
 
# printing original string
print("The original string is : " + str(test_str))
 
# Using nested replace()
# Replace multiple characters at once
res = test_str.replace('a', '%temp%').replace('b', 'a').replace('%temp%', 'b')
 
# printing result
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
 
# initializing string
test_str = "abbabba"
 
# printing original string
print("The original string is : " + str(test_str))
 
# Using translate() + maketrans()
# Replace multiple characters at once
res = test_str.translate(string.maketrans("ab", "ba"))
 
# printing result
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
 
# initializing string
test_str = "34a7bb86abba032"
 
# printing original string
print("The original string is : " + str(test_str))
 
# Using nested replace()
# Replace multiple characters at once
res, n = re.subn('[0-9]', '', test_str)
 
# printing result
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

# define the input string
test_str = "abbabba"
# printing original string
print("The original string is : " + str(test_str))
 
# use a list comprehension to iterate through the string and replace each character
# if the character is 'a', replace it with 'b'
# if the character is 'b', replace it with 'a'
# if the character is anything else, leave it unchanged
new_str = ''.join(['a' if char == 'b' else 'b' if char == 'a' else char for char in test_str])
 
# print the new string
print("The string after replacement of positions : " +new_str)
#This code is contributed by Jyothi pinjala.

                    

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

# initializing string
test_str = "abbabba"
 
# printing original string
print("The original string is : " + str(test_str))
 
# Using dictionary to map characters to their replacements
# Replace multiple characters at once
replacements = {'a': 'b', 'b': 'a'}
replaced_chars = [replacements.get(char, char) for char in test_str]
res = ''.join(replaced_chars)
 
# printing result
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
 
# initializing string
test_str = "abbabba"
 
# printing original string
print("The original string is : " + str(test_str))
 
# Using re.sub() method with regular expression to replace multiple characters
# Replace multiple characters using regular expression
replacements = {'a': 'b', 'b': 'a'}
pattern = '|'.join(replacements.keys())
res = re.sub(pattern, lambda match: replacements[match.group(0)], test_str)
 
# printing result
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.



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