.replace | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

.replace

Guys if i have a code like this: Txt= "abcdabcd" New_txt= txt.replace("a", "1") Print (new_txt) Its possible to replace, for example, a and b in the same .replace line? Or i have do make a new line to change b?

25th Jul 2019, 11:21 AM
Alix Carmo
Alix Carmo - avatar
3 Answers
+ 7
An other approach for multiple replacement is using maketrans and translate: # sample with translate intab = "aeiou" outtab = "12345" trstab = str.maketrans(intab, outtab) str = "this is ground control to major Tom" print(str) print(str.translate(trstab)) # output: th3s 3s gr45nd c4ntr4l t4 m1j4r T4m # ---------- trans = str.maketrans('ae', 'bx') # a->b and e->x strText = 'abcdef' print(strText.translate(trans)) # output: bbcdxf
25th Jul 2019, 1:20 PM
Lothar
Lothar - avatar
+ 6
you can also try this: use a dict with all the replacing pairs: table ={'a':'1', 'b':'2'} txt= "abcdabcd" print('original string: ',txt) # only for demo for i in table: txt = txt.replace(i,table.get(i)) print('final string: ',txt) # only for demo
25th Jul 2019, 12:43 PM
Lothar
Lothar - avatar
+ 2
Thank you all for helping me!!!
25th Jul 2019, 1:22 PM
Alix Carmo
Alix Carmo - avatar