检查句子是否包含符号

时间:2016-11-16 16:40:49

标签: python string python-3.x

string="I can't wait for Christmas!!"
other_symbols='''!()-[]{};:\<>/?#$%^&*_~'''
if other_symbols in string:
   print('wrong')
else:
   print('right')

应该忽略@以外的每个符号,我的输出应该是错误的,但我一直都是正确的。

1 个答案:

答案 0 :(得分:3)

使用any检查other_symbols中的任何符号是否在cavs中。最好为cavs成员资格测试设置O(1)

sc = set(cavs)
if any(i in sc for i in other_symbols):
    print("wrong")
else:
    print("right")

或者,正如@Steven Rumbalski在评论中指出的那样,您可以将其反转并使other_symbols成为一个集合并执行:

if any(c in other_symbols for c in cavs):
    # rest similar

如果要测试多个句子,这将是一种改进,因为您不必为每个句子创建一个集合。