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

.replace

guys, why this didnt work? txt = input("") #for example input is ab def one(): nt = txt.replace("a", "") b = txt.replace("b", "") print(nt) print(b) one() #output b a i tried also: txt= input("")#input ab def one(): nt = txt.replace("a", "") nt = txt.replace("b", "") print(nt) one() #outpu a why this dont replace everything?

3rd Aug 2019, 1:41 PM
Alix Carmo
Alix Carmo - avatar
10 Answers
+ 7
If you are trying to replace a and b, try this txt= "xaby" def one (): n = txt.replace("a","") b = n.replace ("b","") print (n) print (b) one()
3rd Aug 2019, 2:01 PM
David Ashton
David Ashton - avatar
+ 5
For fun, try this user_txt = input() def remove_lc_letters(txt): """Sequentially remove lower case letters.""" for i in range(97, 123): txt = txt.replace(chr(i), "") print(txt) remove_lc_letters(user_txt)
3rd Aug 2019, 2:11 PM
David Ashton
David Ashton - avatar
+ 5
David Ashton ur code is good But when i input :abcd.. Output: abcd bcd cd d # all fine upto thz... But in this case input: fun Output: Fun Fun Fun Fun Fun un un un un n n n n.. Why many line output instead of fun un n.. Also in code y u used range(97,123)... Please explain
3rd Aug 2019, 2:18 PM
Sujithra
+ 5
Cbr✔[ Not Active ] thnq for explaining.😊
4th Aug 2019, 6:32 AM
Sujithra
3rd Aug 2019, 2:10 PM
Sujithra
+ 4
Here's version 2.0: only prints if letter removed user_txt = input() def remove_lc_letters(txt): """Sequentially remove lower case letters.""" for i in range(97, 123): if chr(i) in txt: txt = txt.replace(chr(i), "") print(txt) remove_lc_letters(user_txt)
3rd Aug 2019, 2:40 PM
David Ashton
David Ashton - avatar
3rd Aug 2019, 1:49 PM
Sujithra
+ 3
OK Here's version 3.0 - replaces upper and lower case letters and spaces. user_txt = input() or "Hello World!" def remove_lc_letters(txt): """Sequentially remove upper and lower case letters and spaces. """ for i in range(65, 91): if chr(i) in txt: txt = txt.replace(chr(i), "") print(txt) if chr(i + 32) in txt: txt = txt.replace(chr(i + 32), "") print(txt) if " " in txt: txt = txt.replace(" ", "") print(txt) remove_lc_letters(user_txt) https://code.sololearn.com/csMG5c6LA4fZ/?ref=app
3rd Aug 2019, 3:05 PM
David Ashton
David Ashton - avatar
+ 3
Reminds me of this silly code https://code.sololearn.com/cyVMX5BsatD7
3rd Aug 2019, 3:09 PM
David Ashton
David Ashton - avatar
0
damn sorry the right code is this: def one(): nt = txt.replace("a", "1") nt = txt.replace("b", "2") print(nt) one() when i input ab or whatever it only replaces b, why dont replace a to?
3rd Aug 2019, 2:00 PM
Alix Carmo
Alix Carmo - avatar