[英]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.