ADVERTISEMENT
ADVERTISEMENT

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 »



ADVERTISEMENT


ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.