Q:

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

belongs to collection: Python Lambda Function Programs

0

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 (ch1ch2), 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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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!

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Intersection of two arrays using Lambda expression... >>
<< Python program to find the sum of elements of a li...