Python – Replace multiple characters at once



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 which can perform this particular task. Let’s discuss certain ways in which this task can be performed.

Method #1 : 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 code to demonstrate working of
# Replace multiple characters at once
# Using nested replace()
 
# 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 : Using translate() + maketrans()
There is also a dedication function which 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.

# Python code to demonstrate working of
# Replace multiple characters at once
# Using translate() + maketrans()
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

Last Updated on November 13, 2021 by admin

Leave a Reply

Your email address will not be published. Required fields are marked *

Recommended Blogs