Python – Replace Different characters in String at Once
Last Updated :
26 Apr, 2023
Given a mapping of characters to be replaced with corresponding values, perform all replacements at one, in one-liner.
Input : test_str = 'geeksforgeeks is best', map_dict = {'e':'1', 'b':'6'}
Output : g11ksforg11ks is 61st
Explanation : All e are replaced by 1 and b by 6.
Input : test_str = 'geeksforgeeks', map_dict = {'e':'1', 'b':'6'}
Output : g11ksforg11ks
Explanation : All e are replaced by 1 and b by 6.
Method #1 : Using join() + generator expression
In this, we perform the task of getting characters present in the dictionary and map them to their values by dictionary access, all other characters are appended unchanged, and the result is converted back to the dictionary using join() method.
Python3
test_str = 'geeksforgeeks is best'
print ( "The original string is : " + str (test_str))
map_dict = { 'e' : '1' , 'b' : '6' , 'i' : '4' }
res = ''.join(
idx if idx not in map_dict else map_dict[idx] for idx in test_str)
print ( "The converted string : " + str (res))
|
Output
The original string is : geeksforgeeks is best
The converted string : g11ksforg11ks 4s 61st
Time complexity : O(n)
Space complexity : O(n)
Method #2 : Using regex + lambda
This is complex way to approach problem. In this, we construct appropriate regex using lambda functions and perform the required task of replacement.
Python3
import re
test_str = 'geeksforgeeks is best'
print ( "The original string is : " + str (test_str))
map_dict = { 'e' : '1' , 'b' : '6' , 'i' : '4' }
res = re. compile ( "|" .join(map_dict.keys())).sub( lambda ele: map_dict[re.escape(ele.group( 0 ))], test_str)
print ( "The converted string : " + str (res))
|
Output
The original string is : geeksforgeeks is best
The converted string : g11ksforg11ks 4s 61st
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3 : Using keys() and replace() methods
Python3
test_str = 'geeksforgeeks is best'
print ( "The original string is : " + str (test_str))
map_dict = { 'e' : '1' , 'b' : '6' , 'i' : '4' }
for i in test_str:
if i in map_dict.keys():
test_str = test_str.replace(i,map_dict[i])
print ( "The converted string : " + str (test_str))
|
Output
The original string is : geeksforgeeks is best
The converted string : g11ksforg11ks 4s 61st
Time complexity : O(n^2)
Space complexity : O(n)
Method #4: Using List comprehension
Here are the steps:
Initialize string and mapping dictionary, same as in the previous methods.
Use list comprehension to loop over each character in the string, replacing it with the corresponding value from the dictionary if it exists. If it does not exist, simply append the original character to the new string.
Join the list back into a string using the join() method.
Print the original and converted strings.
Python3
test_str = 'geeksforgeeks is best'
map_dict = { 'e' : '1' , 'b' : '6' , 'i' : '4' }
new_str = ''.join([map_dict.get(char, char) for char in test_str])
print ( "The original string is : " + str (test_str))
print ( "The converted string : " + str (new_str))
|
Output
The original string is : geeksforgeeks is best
The converted string : g11ksforg11ks 4s 61st
Time complexity: O(n), where n is the length of the input string.
Auxiliary space: O(n), where n is the length of the input string.
Method #5: Using reduce():
Algorithm:
- Import the reduce function from the functools library.
- Initialize the input string test_str and the mapping dictionary map_dict.
- Use reduce function to apply the lambda function on each key-value pair in the map_dict dictionary and
- replace the characters in the input string test_str.
- The lambda function checks if the character from the dictionary is present in the input string test_str. If yes, then it replaces the character with the corresponding value from the dictionary, otherwise, it returns the original string.
- The final output string converted_str is returned after all the characters have been replaced.
- Print the original string and the converted string.
Python3
from functools import reduce
test_str = 'geeksforgeeks is best'
map_dict = { 'e' : '1' , 'b' : '6' , 'i' : '4' }
converted_str = reduce ( lambda s, kv: s.replace(kv[ 0 ], kv[ 1 ]) if kv[ 0 ] in s else s, map_dict.items(), test_str)
print ( "The original string is : " + str (test_str))
print ( "The converted string : " + str (converted_str))
|
Output
The original string is : geeksforgeeks is best
The converted string : g11ksforg11ks 4s 61st
Time Complexity:
The time complexity of this code is O(n^2), where n is the length of the input string test_str.
This is because the replace method of string has a time complexity of O(n), and we are using it inside a loop which also has a time complexity of O(n).
Space Complexity:
The space complexity of this code is O(n), where n is the length of the input string test_str.
This is because we are creating a new string every time we replace a character. So, the space required to store the final output string is also O(n).
Please Login to comment...