Computer >> Computer tutorials >  >> Programming >> Python

Map function and Lambda expression in Python to replace characters


We want to replace a character a1 with a character a2 and a2 with a1. For example,

For the input string,

"puporials toinp"

and characters p and t, we want the end string to look like −

"tutorials point"

For this we can use map function and lambdas to make the replacement. The map(lambda, input) function iterates over each item passed to it(in form of iterable input) and apply the lambda expression to it. So we can use it as follows −

Example

def replaceUsingMapAndLambda(sent, a1, a2):
# We create a lambda that only works if we input a1 or a2 and swaps them.
newSent = map(lambda x: x if(x != a1 and x != a2) else a1 if x == a2 else a2, sent)
return ''.join(newSent)

print(replaceUsingMapAndLambda("puporials toinp", "p", "t"))

Output

This will give the output −

tutorials point