[Solved] The Spy Life (Don't use parenthesis inside character class.) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 5

[Solved] The Spy Life (Don't use parenthesis inside character class.)

I tried to solved "The Spy Life" challenge by the following code and it worked well for test cases 1,2,4,5 but it fails in test case 3 which is hidden for me and I can see whats the problem to resolve it. Can anyone please see whats the problem of this code and how to fix it? The task is to take a string from input, invert it and remove any character that is not a letter or space and output the decoded message. My code: import re msg = input()[::-1] pattern = r"[^(a-zA-Z\s)]+" decoded_msg = re.sub(pattern,"",msg) print(decoded_msg) Example Input: t`a=e+r8g 9e78r3a4 u^o%y* Output: you are great

21st Mar 2022, 10:39 PM
Siavash Kardar Tehran
Siavash Kardar Tehran - avatar
5 Answers
+ 1
#1 way txt = input() t2 = ''.join(i for i in txt if i.isalpha() or i==' ') print(t2[::-1]) #2 way txt = input() t2 = '' for i in txt: if i.isalpha() or i==' ': t2+=i print(t2[::-1])
22nd Mar 2022, 3:31 AM
Shadoff
Shadoff - avatar
+ 1
22nd Mar 2022, 7:30 AM
CodeStory
CodeStory - avatar
0
If the use of RegEx is optional, you could try validating each character instead, like: msg = input()[::-1] decoded_msg = “”.join([c for c in msg if c.isalpha() or c.isspace()]) print(decoded_msg) This will use a list comprehension to create a list of characters that are a letter or a space, then join the list to create the output string. Hopefully, this will fix the hidden test case.
21st Mar 2022, 11:13 PM
Brian
0
Brian Alexis Your code raises "SyntaxError"
21st Mar 2022, 11:24 PM
Siavash Kardar Tehran
Siavash Kardar Tehran - avatar
0
Siavash Kardar Tehran Try rewriting the double quotes in line 2 (“”.join()) yourself, it seems to be a SoloLearn or my keyboard formatting issue. It worked for me after rewriting.
21st Mar 2022, 11:43 PM
Brian