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 : geeksforgeeks
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
def replaceChars( input ,c1,c2):
newChars = map ( lambda x: x if (x! = c1 and x! = c2) else \
c1 if (x = = c2) else c2, input )
print (''.join(newChars))
if __name__ = = "__main__" :
input = 'grrksfoegrrks'
c1 = 'e'
c2 = 'r'
replaceChars( input ,c1,c2)
|
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
27 Jul, 2022
Like Article
Save Article