CAVS CAVS - 18 days ago 5
Python Question

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.

Answer

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.

Comments