简体   繁体   中英

checking if a sentence contains Symbols

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

It is supposed to ignore every symbol other than @ and my output should be wrong but I keep getting right.

Use any to check if any of the symbols in other_symbols is in cavs . Better make cavs a set too for O(1) membership tests:

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

Or, as @Steven Rumbalski pointed out in a comment, you could reverse it and make other_symbols a set and do:

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

This would be an improvement if there were multiple sentences to test since you wouldn't have to create a set for each sentence.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM