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.
Input : str = 'grrksfoegrrks' c1 = e, c2 = r Output : geeksforgeeks Input : str = 'ratul' c1 = t, c2 = h Output : rahul
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
We have existing solution for this problem in C++ please refer Replace a character c1 with c2 and c2 with c1 in a string S link. We will solve this problem quickly in Python using Lambda expression and map() function. We will create a lambda expression where character c1 in string will be replaced by c2 and c2 will be replaced by c1 and other will remain same, then we will map this expression on each character of string and will get updated string.