Friday, September 26, 2025
HomeLanguagesMap function and Lambda expression in Python to replace characters

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 : neveropen 

Input : str = 'ratul'
        c1 = t, c2 = h 
Output : rahul

We have an existing solution for this problem in C++. Please refer to Replace a character c1 with c2 and c2 with c1 in a string S. We can solve this problem quickly in Python using a Lambda expression and the 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. All other characters will remain the same. Then we will map this expression on each character of string and return an updated string. 

Implementation:

Python3




# 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)


Output

neveropen
RELATED ARTICLES

Most Popular

Dominic
32320 POSTS0 COMMENTS
Milvus
84 POSTS0 COMMENTS
Nango Kala
6683 POSTS0 COMMENTS
Nicole Veronica
11854 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11910 POSTS0 COMMENTS
Shaida Kate Naidoo
6795 POSTS0 COMMENTS
Ted Musemwa
7071 POSTS0 COMMENTS
Thapelo Manthata
6755 POSTS0 COMMENTS
Umr Jansen
6762 POSTS0 COMMENTS