Map() Function and Lambda Expression in Python to Replace Characters

Learn how to replace the given characters of a string using map() function and lambda expression in Python?
Submitted by IncludeHelp, on March 08, 2022

Given a string (str), and characters (ch1, ch2) to replace, we have to replace ch1 with ch2 and ch2 with ch1 using map() function and lambda expression.

Example:

Input:
str = 'He00l wlrod!'
ch1 = 'l'
ch1 = 'o'

Output: 'Hello world!'

In the below solution, we will use a map() function and lambda expression to replace the characters within the given string. There will be a string (str), and two characters (ch1, ch2), by using the combination of the map() and Lambda expression, we will replace the characters i.e., ch1 with ch2 and ch2, other characters will remain the same.

Python code to replace characters using map() function and Lambda expression

# Function to replace characters
# Here, we will assign the string 
# in which replacement will be done
# and, two characters to be replaced 
# with each other

def replace(s,c1,c2):
    # Lambda expression to replace c1 with c2
    # and c2 with c1
     new = map(lambda x: x if (x!=c1 and x!=c2) else \
                c1 if (x==c2) else c2,s)
  
     # Now, join each character without space
     # to print the resultant string
     print (''.join(new))
  
# main function
if __name__ == "__main__":
    str = 'Heool wlrod!'
    ch1 = 'l'
    ch2 = 'o'
    
    print("Original string is:", str)
    print("Characters to replace:", ch1, "and", ch2)
    
    print("String after replacement:")
    replace(str,ch1,ch2)

Output:

Original string is: Heool wlrod!
Characters to replace: l and o
String after replacement:
Hello world!

Python Lambda Function Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.