简体   繁体   English

如何创建用于删除不需要的字符并在Python中替换它们的for循环

[英]How to create a for-loop that removes unwanted characters and replaces them in Python

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. 因此,例如,该程序应该能够将“ Anna”和“ A!N!N!A”都解释为回文。 I'm required to use a for-loop to remove the characters. 需要使用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()

So what I need is a for-loop that can help me to get the not_valid characters out of text . 因此,我需要一个for循环,可以帮助我从text获取not_valid字符。 All the code I've been trying with so far Is useless. 到目前为止,我一直在尝试的所有代码都没有用。 I would be really grateful for all the help I can get! 我将非常感谢我能获得的所有帮助!

you can use regex module and sub function 您可以使用正则表达式模块和sub功能

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循环

for c in bad_chars:
    s = s.replace(c, '')

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. 对于更“简单”的答案(尽管我个人认为第一个答案很简单),您可以遍历每个字母,然后使用in关键字检查该字母是否为not_valid字母之一。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM