我正在编写一个程序,检查用户输入的单词或句子是否是回文。这是目前为止的程序:删除另一个列表中的列表中的成员
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 a palindrome."
else:
print "No, 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'
好了,所以我已经改变了变量的名字,我没有得到上面的错误。现在我仍然不知道如何减去列表中的元素。
由于我是初学者程序员,这可能对你来说很愚蠢。如果是这样的话,我很抱歉。如果有人能解决我遇到的两个问题中的一个或两个,我会非常感激。在此先感谢您的帮助。对不起,英文不好,文章太长:)
不要使用字符串作为变量名,然后尝试使用string模块 – 2014-10-19 20:08:02
你说得对,我不知道 – chilliefiber 2014-10-19 20:10:25
不叫'STR()'从返回的值'raw_input()'它已经有'str'类型。 – jfs 2014-10-19 20:12:51