Python | python str replace multiple
ThereplacementofonecharacterwithanotherisacommonproblemthateveryPython[1]programmerwouldhaveworkedwithinthepast.Butsometimes,werequireasimpleone-linesolutionthatcanperformthisparticulartask.Let’sdiscusscertainwaysinwhichthistaskcanbeperformed. Method1:Replacemultiplecharactersusingnestedreplace() [2]Thisproblemcanbesolvedusingthenestedreplacemethod,whichinternallywouldcreateatemp.variabletoholdtheintermediatereplacementstate. Python3test_str="abbabba" print("Theoriginalstringis:"+str(test_st...
The replacement of one character with another is a common problem that every Python[1] programmer would have worked with in the past. But sometimes, we require a simple one-line solution that can perform this particular task. Let’s discuss certain ways in which this task can be performed.
Method 1: Replace multiple characters using nested replace() [2]This problem can be solved using the nested replace method, which internally would create a temp. variable to hold the intermediate replacement state.
Python3test_str = "abbabba"
print("The original string is : " + str(test_str))
res = test_str.replace(a, %temp%).replace(b, a).replace(%temp%, b)
print("The string after replacement of positions : " + res)
Output:
The original string is : abbabba The string after replacement of positions : baabaabTime Complexity: O(n)Auxil...