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) |
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) |
The original string is : abbabba The string after replacement of positions : baabaab
Recommended Posts:
- Python | Replace multiple occurrence of character by single
- Map function and Lambda expression in Python to replace characters
- replace() in Python to replace a substring
- Python | Pandas Series.str.replace() to replace text in a series
- Python String | replace()
- Python | Pandas Timestamp.replace
- Python | Pandas dataframe.replace()
- Python | Pandas Series.replace()
- Python | Replace sublist with other in list
- Python | sympy.replace() method
- Python | Replace NaN values with average of columns
- Python | Replace substring in list of strings
- Python | Replace negative value with zero in numpy array
- Python | Convert list of strings and characters to list of characters
- Python | Replace list elements with its ordinal number
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



