Reverse-Replace Python function | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Reverse-Replace Python function

Hi, I need an inverse to replace function in Python. This is the example: a = 'Whisky in a jar' #If I use the normal regular way (not-inverse one) a.replace('a', '_') a = 'Whisky in _ j_r' #But I need the exact opposite. I need it to return like this: a = '______ __ a _a_' What code should I use?

24th Jun 2019, 4:52 AM
Esteban Perez-Ortiz
Esteban Perez-Ortiz - avatar
5 Answers
+ 3
Replace works like this: res = "" for i in a: if i=="whatever I need": res+='replacement' else: res+=i That's how replace works. So if you want to EXCLUDE those words, then replace the equality with an inequality, aka if i!="whatever I need"
24th Jun 2019, 5:07 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 2
# I got solution try this: a = "Whiskey in a kar" for i in a: if i!='a': a=a.replace(i,'_') print(a) #To run this simply paste it to python console # Hope this helps😄
24th Jun 2019, 5:07 AM
Deepak Kumar
Deepak Kumar - avatar
+ 1
Esteban Perez-Ortiz Thank you. Actually, if you want to use the syntax a.inverse_replace(x, y) instead of inverse_replace(string, x, y), you have to make it a class: https://code.sololearn.com/cod746MgqEfc/?ref=app
24th Jun 2019, 5:49 AM
Anna
Anna - avatar
0
@Anna, I believe your response is correct. Thank you very much. And thank you guys as well.
24th Jun 2019, 5:27 AM
Esteban Perez-Ortiz
Esteban Perez-Ortiz - avatar