[英]How to create a for-loop that removes unwanted characters and replaces them in Python
我的任务是建立回文检测器,代码中只剩下一件事,我无法理解。 我已经尝试修复了好几天,现在我需要一些帮助,然后我才会失去理智...
该程序剩下的唯一一件事就是从用户输入中删除不需要的字符,然后将其替换为任何内容(“”)。 因此,例如,该程序应该能够将“ Anna”和“ A!N!N!A”都解释为回文。 我需要使用for循环来删除字符。
> #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()
因此,我需要一个for循环,可以帮助我从text
获取not_valid
字符。 到目前为止,我一直在尝试的所有代码都没有用。 我将非常感谢我能获得的所有帮助!
您可以使用正则表达式模块和sub
功能
import re
s = re.sub(r'[?!\"\'#€%&\-()=\s:,]', '', s)
s = re.sub(r'\W', '', s) # this will remove all non-alphanumerical chars
与for循环
for c in bad_chars:
s = s.replace(c, '')
对于更“简单”的答案(尽管我个人认为第一个答案很简单),您可以遍历每个字母,然后使用in
关键字检查该字母是否为not_valid
字母之一。
这是一个例子:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.