Python – Replace Different characters in String at Once
Given a mapping of characters to be replaced with corresponding values, perform all replaces 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 dictionary and map them to their values by dictionary access, all other characters are appended unchanged, the result is converted back to dictionary using join().
Python3
# Python3 code to demonstrate working of# Replace Different characters in String at Once# using join() + generator expression# initializing stringtest_str = 'geeksforgeeks is best'# printing original Stringprint("The original string is : " + str(test_str))# initializing mapping dictionarymap_dict = {'e':'1', 'b':'6', 'i':'4'}# generator expression to construct vals# join to get stringres = ''.join(idx if idx not in map_dict else map_dict[idx] for idx in test_str)# printing resultprint("The converted string : " + str(res)) |
The original string is : geeksforgeeks is best The converted string : g11ksforg11ks 4s 61st
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
# Python3 code to demonstrate working of# Replace Different characters in String at Once# using regex + lambdaimport re# initializing stringtest_str = 'geeksforgeeks is best'# printing original Stringprint("The original string is : " + str(test_str))# initializing mapping dictionarymap_dict = {'e':'1', 'b':'6', 'i':'4'}# using lambda and regex functions to achieve taskres = re.compile("|".join(map_dict.keys())).sub(lambda ele: map_dict[re.escape(ele.group(0))], test_str)# printing resultprint("The converted string : " + str(res)) |
The original string is : geeksforgeeks is best The converted string : g11ksforg11ks 4s 61st


 (2).jpg)
