Open In App

Python – Replace Different characters in String at Once

Last Updated : 26 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




# Python3 code to demonstrate working of
# Replace Different characters in String at Once
# using join() + generator expression
 
# initializing string
test_str = 'geeksforgeeks 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))


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




# Python3 code to demonstrate working of
# Replace Different characters in String at Once
# using regex + lambda
import re
 
# initializing string
test_str = 'geeksforgeeks 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))


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




# Python3 code to demonstrate working of
# Replace Different characters in String at Once
 
# initializing string
test_str = 'geeksforgeeks 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))


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




# initializing string
test_str = 'geeksforgeeks 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))


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:

  1. Import the reduce function from the functools library.
  2. Initialize the input string test_str and the mapping dictionary map_dict.
  3. Use reduce function to apply the lambda function on each key-value pair in the map_dict dictionary and
  4. replace the characters in the input string test_str.
  5. 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.
  6. The final output string converted_str is returned after all the characters have been replaced.
  7. Print the original string and the converted string.

Python3




# Importing reduce from functools
from functools import reduce
 
# Initializing the string
test_str = 'geeksforgeeks 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


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).



Similar Reads

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 that can perform this particular task. Let's discuss certain ways in which this task can be performed. Method 1: Replace multiple characters using nested replace() Th
6 min read
replace() in Python to replace a substring
Given a string str that may contain one more occurrences of “AB”. Replace all occurrences of “AB” with “C” in str. Examples: Input : str = "helloABworld" Output : str = "helloCworld" Input : str = "fghABsdfABysu" Output : str = "fghCsdfCysu" This problem has existing solution please refer Replace all occurrences of string AB with C without using ex
1 min read
Python | Pandas Series.str.replace() to replace text in a series
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages that makes importing and analyzing data much easier. Pandas Series.str.replace() method works like Python .replace() method only, but it works on Series too. Before calling .replace() on a Panda
5 min read
Map function and Lambda expression in Python to replace characters
Given a string S, c1 and c2. Replace character c1 with c2 and c2 with c1. Examples: Input : str = 'grrksfoegrrks' c1 = e, c2 = r Output : geeksforgeeks Input : str = 'ratul' c1 = t, c2 = h Output : rahul We have an existing solution for this problem in C++. Please refer to Replace a character c1 with c2 and c2 with c1 in a string S. We can solve th
2 min read
Python | Replace characters after K occurrences
Sometimes, while working with Python strings, we can have a problem in which we need to perform replace of characters after certain repetitions of characters. This can have applications in many domains including day-day and competitive programming. Method #1: Using loop + string slicing This is brute force way in which this problem can be solved. I
5 min read
Python program to Replace all Characters of a List Except the given character
Given a List. The task is to replace all the characters of the list with N except the given character. Input : test_list = ['G', 'F', 'G', 'I', 'S', 'B', 'E', 'S', 'T'], repl_chr = '*', ret_chr = 'G' Output : ['G', '*', 'G', '*', '*', '*', '*', '*', '*'] Explanation : All characters except G replaced by * Input : test_list = ['G', 'F', 'G', 'B', 'E
4 min read
Python program to print k characters then skip k characters in a string
Given a String, extract K characters alternatively. Input : test_str = 'geeksgeeksisbestforgeeks', K = 4 Output : geekksisforg Explanation : Every 4th alternate range is sliced. Input : test_str = 'geeksgeeksisbest', K = 4 Output : geekksis Explanation : Every 4th alternate range is sliced. Method #1 : Using loop + slicing In this, we perform task
5 min read
Modify the string such that it contains all vowels at least once
Given a string S containing only Uppercase letters, the task is to find the minimum number of replacement of characters needed to get a string with all vowels and if we cannot make the required string then print Impossible. Examples: Input: str = "ABCDEFGHI"Output: AOUDEFGHIExplanation: There are already 3 Vowels present in the string A, E, I we ju
12 min read
How to apply different titles for each different subplots using Plotly in Python?
Prerequisites: Python Plotly In this article, we will explore how to apply different titles for each different subplot. One of the most deceptively-powerful features of data visualization is the ability for a viewer to quickly analyze a sufficient amount of information about data when pointing the cursor over the point label appears. It provides us
2 min read
Replace Characters in Strings in Pandas DataFrame
In this article, we are going to see how to replace characters in strings in pandas dataframe using Python. We can replace characters using str.replace() method is basically replacing an existing string or character in a string with a new one. we can replace characters in strings is for the entire dataframe as well as for a particular column. Synta
3 min read
Practice Tags :