我创建了一个函数,它接受一个单词和一串“禁止的”字母,如果单词没有使用任何字母,则返回True。
def avoids(word,forbidden):
for letter in word:
if letter in forbidden:
return False
else:
return True我想对此进行修改,以便不使用“禁止”作为要避免的字母,而是提示用户放置几个字母,并打印不包含任何字母的单词数量。我还有一个.txt文档,其中包含了这些单词,以使它变得有趣。
这就是我提出的错误之处。我想要一些帮助和教育,如果可能的话,因为我的‘在线’老师从来没有在身边提供帮助。请帮助:)
def word_no_forbidden():
forbidden = input('pick 5 letters')
fin = open('words1.txt')
no_forbidden_word = 0
for line in fin:
word = line.strip()
for letter in word:
if forbidden in word:
continue
print word这是我得到的错误,我理解它,但是,我不确定如何处理这个问题……
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
word_no_forbidden()
File "C:/Python27/test.py", line 9, in word_no_forbidden
if forbidden in word:
TypeError: 'in <string>' requires string as left operand, not tuple发布于 2011-09-23 07:44:42
def word_no_forbidden():
forbidden = raw_input('pick 5 letters')
fin = open('words1.txt')
no_forbidden_word = 0
for line in fin:
word = line.strip()
for letter in list(word):
if letter in forbidden:
break
else:
print word备注:
正如温斯顿所说的那样,1>使用raw_input
2>如果要遍历字符串,请使用list(your_string)获取字符列表
3>这里的else仅在我们的for letter in list(word)循环完成而不会中断时执行(换句话说,没有禁止的字母)
发布于 2011-09-23 07:32:29
我猜..。
你是python 2.x
当你运行你输入的程序时:
'a','b','c','d'在Python2.x上,您希望使用raw_input而不是input。这将给出一个字符串,其中包含您键入的内容。事实上,python会试图将您所理解的任何内容解释为python表达式,这是危险的,而且通常是一个糟糕的想法。
您的第二个问题是您颠倒了第一个示例中的代码行letter in forbidden,因此它变成了不同于forbidden in word的代码行。
发布于 2011-09-23 07:31:16
要从用户读入字符串,应该使用raw_input,而不是input。input尝试将用户输入的字符串实际计算为Python代码,这可能会导致您得到一个意外的数据类型(或者其他更糟糕的情况)。
相反,raw_input总是返回一个字符串。
(注意:这仅适用于Python 2.x。从Python3开始,raw_input被重命名为input,并且没有input曾经执行的功能。)
https://stackoverflow.com/questions/7522569
复制相似问题