Given a mapping of characters to be replaced with corresponding values, perform all replacements at one, in one-liner.
Input : test_str = 'neveropen 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 = 'neveropen', 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
# Python3 code to demonstrate working of # Replace Different characters in String at Once # using join() + generator expression # initializing string test_str = 'neveropen is best' # printing original String print ( "The original string is : " + str (test_str)) # initializing mapping dictionary map_dict = { 'e' : '1' , 'b' : '6' , 'i' : '4' } # generator expression to construct vals # join to get string res = ''.join( idx if idx not in map_dict else map_dict[idx] for idx in test_str) # printing result print ( "The converted string : " + str (res)) |
The original string is : neveropen 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
# Python3 code to demonstrate working of # Replace Different characters in String at Once # using regex + lambda import re # initializing string test_str = 'neveropen is best' # printing original String print ( "The original string is : " + str (test_str)) # initializing mapping dictionary map_dict = { 'e' : '1' , 'b' : '6' , 'i' : '4' } # using lambda and regex functions to achieve task res = re. compile ( "|" .join(map_dict.keys())).sub( lambda ele: map_dict[re.escape(ele.group( 0 ))], test_str) # printing result print ( "The converted string : " + str (res)) |
The original string is : neveropen is best The converted string : g11ksforg11ks 4s 61st
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3 : Using keys() and replace() methods
Python3
# Python3 code to demonstrate working of # Replace Different characters in String at Once # initializing string test_str = 'neveropen is best' # printing original String print ( "The original string is : " + str (test_str)) # initializing mapping dictionary 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]) # printing result print ( "The converted string : " + str (test_str)) |
The original string is : neveropen 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
# initializing string test_str = 'neveropen is best' # initializing mapping dictionary map_dict = { 'e' : '1' , 'b' : '6' , 'i' : '4' } # using list comprehension new_str = ''.join([map_dict.get(char, char) for char in test_str]) # printing result print ( "The original string is : " + str (test_str)) print ( "The converted string : " + str (new_str)) |
The original string is : neveropen 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
# Importing reduce from functools from functools import reduce # Initializing the string test_str = 'neveropen is best' # Initializing mapping dictionary map_dict = { 'e' : '1' , 'b' : '6' , 'i' : '4' } # Using reduce to replace the characters in the string # lambda function checks if the character from dictionary is present in the string # then replace it, otherwise return the string s as it is # iteratively check each key-value pair in the map_dict converted_str = reduce ( lambda s, kv: s.replace(kv[ 0 ], kv[ 1 ]) if kv[ 0 ] in s else s, map_dict.items(), test_str) # Printing the original and converted string print ( "The original string is : " + str (test_str)) print ( "The converted string : " + str (converted_str)) #This code is contributed by Vinay pinjala |
The original string is : neveropen 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).