Reputation: 3
I have an assignment which is to build a palindrome detector, and there is just one thing left in the code that I can't get my head around. I've been trying to fix it for days and now I need some assistance before I lose my mind...
The only thing left is for the program to remove unwanted characters from the users input, and replace it with nothing (""). So for example, the program is supposed to be able to interpret both "Anna" and "A!N!N!A" as palindromes. I'm required to use a for-loop to remove the characters.
> #the characters that need to be removed
not_valid = "?!\"\'#€%&/-()=? :,"
#user input
user_entry = tkinter.Entry(mid_frame, width = 67)
#variable with the user input, and transforms into lower case characters
text = user_entry.get()
text = text.lower()
So what I need is a for-loop that can help me to get the not_valid
characters out of text
. All the code I've been trying with so far Is useless. I would be really grateful for all the help I can get!
Upvotes: 0
Views: 166
Reputation:
For a more "simple" answer (although I personally think the first answer is simple enough) you can loop through each letter, then use the in
keyword to check if that letter is one of the not_valid
letters.
Here is an example:
text = user_entry.get()
text = text.lower()
not_valid = "?!\"\'#€%&/-()=? :,"
valid = "" #Create a new_variables were only the valid characters are stored
for char in text: #For every character in the text...
if char in not_valid: #If the character is in your not_valid list do not add it
continue
else: #Other wise add it
valid += char
print(valid)
Upvotes: 0
Reputation: 4313
you can use regex module and sub
function
import re
s = re.sub(r'[?!\"\'#€%&\-()=\s:,]', '', s)
s = re.sub(r'\W', '', s) # this will remove all non-alphanumerical chars
with for loop
for c in bad_chars:
s = s.replace(c, '')
Upvotes: 2