我的错误出现在这一行:
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
之外的其他内容吗?应该是什么?
答案 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
操作数时,左侧和右侧对象必须是同一类型。在这种情况下,exclude3
是set
对象,您无法在字符串中检查其成员身份。
示例:
>>> [] 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