+ 1
Please somebody tell me why the code is not working?
I was solving the 'The spy life' problem in the community section.Here's the code; def message(spy): char="@#
amp;&/?!*;:-+£¢€¥√1235467890|π÷׶∆©®%✓\~" for i in char: if i in msg: new=msg.replace(i,"") new2=new[::-1] return new2 msg=input() print(message(msg))6 Answers
+ 3
In if :
new=msg.replace(i,"") # making new string in new
new2=new[::-1] #reversing
return new2 #returning so only first match is replaced , reversed, exit loop..
It will not continue..
instead complete loop by changing **original string.. **After loop, outside if, and loop => reverse it and return.
+ 4
Snehil Pandey Pls don't give finished code as answer, because it makes the OP skip the most important part of learning process. Pls remember this is a learning app.
Instead, prefer giving hints for the OP to find the solution.
+ 1
import re
text = str(input())
result = re.sub(r"[^\w\s]", "", text)
res = re.sub(r"\d", "", result)
def reverse(res):
res = res[::-1]
return res
print (reverse(res))
#I've used regular expression
+ 1
Jayakrishna🇮🇳 Thanks for the suggestion but how can I remove the unwanted letters without looping it.
+ 1
Vaibhav Pandey
If you don't want to use loop then try regex way as in @Snehil Panday code.
re.sub(r"[^\w\s]", "", text) will return all replaced by empty "" char, except a word and space in text string..
re.sub(r"\d", "", text) will return all replaced by empty "" , except digits in the text string.
Alternatively, re.findall(r"[a-zA-Z]", text ) will returns list of all characters from text string. Use join and reverse it just next.. one liner.
0
Jayakrishna🇮🇳 Okay thanks.