python – 删除另一个列表中的列表成员
发布时间:2020-12-20 11:38:29 所属栏目:Python 来源:网络整理
导读:我正在编写一个程序来检查用户输入给出的单词或句子是否是回文.这是迄今为止的计划: def reverse(text): a = text[::-1] if a == text: print "Yes,it's a palindrome." else: print "No,it's not a palindrome."string = str(raw_input("Enter word here:"
我正在编写一个程序来检查用户输入给出的单词或句子是否是回文.这是迄今为止的计划:
def reverse(text): a = text[::-1] if a == text: print "Yes,it's a palindrome." else: print "No,it's not a palindrome." string = str(raw_input("Enter word here:")).lower() reverse(string) 但是,此代码不适用于句子.所以我试着这样做: import string def reverse(text): a = text[::-1] if a == text: print "Yes,it's not a palindrome." notstring = str(raw_input("Enter word here:")).lower() liststring = list(notstring) forbiddencharacters = string.punctuation + string.whitespace listcharacters = list(forbiddencharacters) newlist = liststring - listcharacters finalstring = "".join(newlist) reverse(finalstring) 我的目标是将标点符号和空格放入列表中,然后将这些字符减去用户的输入,这样即使字符串有标点符号和/或空格,程序也可以判断它是否是回文.但是,我不知道如何将列表中的元素减去另一个列表中的元素.我这样做,通过创建另一个等于用户输入减去字符的列表不起作用(我在我的Xubuntu终端模拟器中尝试过).除此之外,当我运行程序时出现此错误: Traceback (most recent call last): File "reverse.py",line 12,in <module> forbiddencharacters = string.punctuation + string.whitespace AttributeError: 'str' object has no attribute 'punctuation' 好的,所以我更改了变量名称,我没有上面的错误.现在我仍然不知道如何减去列表的元素. 由于我是初学程序员,这对你来说似乎很愚蠢.如果是这样的话,我很抱歉.如果有人能解决我遇到的两个问题中的一个或两个,我将非常感激.在此先感谢您的帮助.对不起,英文不好,帖子很长:) 解决方法
你应该添加一些过滤,因为palindromes有各种语法技巧(空格,逗号等).
palindrome = "Rail at a liar" def is_palindrome(text): text = text.lower() #Avoid case issues text = ''.join(ch for ch in text if ch.isalnum()) #Strips down everything but alphanumeric characters return text == text[::-1] if is_palindrome(palindrome): print "Yes,it's a palindrome." else: print "No,it's not a palindrome." (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |