检查输入中是否包含字母

时间:2016-02-02 13:27:36

标签: python set operand

我的错误出现在这一行:

if exclude3 not in Sent:

它是:

TypeError: 'in <string>' requires string as left operand, not set

我的代码是:

import string

Word = input("Please give a word from the sentence")

exclude3 = set(string.ascii_letters)

if exclude3 not in Sent:
    print("")
elif exclude3 not in Word:
    print("")
else:

什么是左操作数?我做错了什么,是否有更简单的方法来实现我想要的?我应该使用in之外的其他内容吗?应该是什么?

3 个答案:

答案 0 :(得分:1)

exclude3不是string,而是set 您尝试使用in运算符检查另一个set中是否包含set错误。

也许你打算写:if Sent not in exclude3

答案 1 :(得分:0)

您需要检查集合和字符串是否重叠。任

if not exclude3.intersection(Sent):

if not any(x in Sent for x in exclude3):

会有所需的结果。

in运算符的工作原理是测试左侧参数是否是右侧参数的元素。例外是str1 in str2,它测试左侧str是否是另一个的子串

答案 2 :(得分:0)

使用in操作数时,左侧和右侧对象必须是同一类型。在这种情况下,exclude3set对象,您无法在字符串中检查其成员身份。

示例:

>>> [] in ''
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not list

如果要检查字符串中所有项目是否存在,可以使用set.intersection(),如下所示:

if exclude3.interection(Sent) == exclude3:
      # do stuff

对于任何交叉点,只需检查exclude3.interection(Sent)的验证:

if exclude3.interection(Sent):
     # do stuff