Skip to content
Related Articles

Related Articles

Python | Replace multiple characters at once

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 12 Sep, 2022
Improve Article
Save Article

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

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

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

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!