Map function and Lambda expression in Python to replace characters

Sometimes we need to swap specific characters in a string. Python's map() function combined with lambda expressions provides an elegant solution for character replacement operations.

Problem Statement

We want to replace character a1 with character a2 and a2 with a1 simultaneously. For example ?

Input string:

"puporials toinp"

Characters to swap: p and t

Expected output:

"tutorials point"

Using map() and Lambda Expression

The map() function applies a lambda expression to each character in the string. The lambda handles the character swapping logic ?

def replaceUsingMapAndLambda(sent, a1, a2):
    # Lambda swaps a1 with a2 and a2 with a1, keeps other characters unchanged
    newSent = map(lambda x: x if(x != a1 and x != a2) else a1 if x == a2 else a2, sent)
    return ''.join(newSent)

result = replaceUsingMapAndLambda("puporials toinp", "p", "t")
print(result)
tutorials point

How It Works

The lambda expression uses conditional logic:

  • x if(x != a1 and x != a2) − keeps character unchanged if it's neither a1 nor a2
  • a1 if x == a2 − replaces a2 with a1
  • a2 − replaces a1 with a2 (else case)

Alternative Approach Using Dictionary

For better readability, we can use a dictionary with get() method ?

def replaceUsingDict(sent, a1, a2):
    char_map = {a1: a2, a2: a1}
    return ''.join(map(lambda x: char_map.get(x, x), sent))

result = replaceUsingDict("puporials toinp", "p", "t")
print(result)
tutorials point

Comparison

Method Readability Performance Best For
Conditional Lambda Medium Good Simple swaps
Dictionary + Lambda High Better Multiple mappings

Conclusion

Using map() with lambda expressions provides a functional approach to character replacement. The dictionary method offers better readability and can easily extend to multiple character mappings.

Updated on: 2026-03-24T20:50:16+05:30

747 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements