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

filter_none

edit
close

play_arrow

link
brightness_4
code

# Function to replace a character c1 with c2 
# and c2 with c1 in a string S 
  
def replaceChars(input,c1,c2):
  
     # create lambda to replace c1 with c2, c2 
     # with c1 and other will remain same 
     # expression will be like "lambda x:
     # x if (x!=c1 and x!=c2) else c1 if (x==c2) else c2"
     # and map it onto each character of string
     newChars = map(lambda x: x if (x!=c1 and x!=c2) else \
                c1 if (x==c2) else c2,input)
  
     # now join each character without space
     # to print resultant string
     print (''.join(newChars))
  
# Driver program
if __name__ == "__main__":
    input = 'grrksfoegrrks'
    c1 = 'e'
    c2 = 'r'
    replaceChars(input,c1,c2)

chevron_right


Output:

geeksforgeeks


My Personal Notes arrow_drop_up

Experienced Software Engineer with a demonstrated history of working in the information technology and services industry Skilled in Big Data technologies, Data Structures, Algorithm, Software Development, App Development, Databases, Python, Java, C, and WordPress

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.