0

I'm trying to make sure that a word variable doesn't contain characters from a forbidden characters list. This all seems to work fine until I enter more than one character however.

For example, code here returns that there are special characters in the string variable as expected.

specialCharacters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-/:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'

string = "a" 
    
if string in specialCharacters:
    print("There are special characters!")
else: 
    print("No special characters found!")

# This prints "There are special characters!"

However, when the string contains two of the same characters from the specialCharacters list, it returns that there are no special characters when it in fact does. Why isn't Python recognising the special characters when there are simply more of it?

specialCharacters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-/:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'

string = "aa"
    
if string in specialCharacters:
    print("There are special characters!")
else: 
    print("No special characters found!")

# This prints "No special characters found!"
  • Because you're attempting to find the substring `"aa"` inside the *superstring* `specialCharacters`, which indeed doesn't contain it. – revliscano Aug 02 '20 at 03:04
  • `in` checks if its left operand is a part of its right operand. `"aa"` is not a part of that long string. That's why. – DYZ Aug 02 '20 at 03:04
  • The linked duplicate answers a different question, but fully explains the behaviour in question. For strings, `in` does a substring search, not a... whatever your reasoning is for why `aa` should be found within that test string. Looking for each character separately, perhaps? – Karl Knechtel Aug 02 '20 at 03:09
  • If you have an actual question about how to get the behaviour you want, then please open a new question and be specific about what the logic is for how you want it to behave. – Karl Knechtel Aug 02 '20 at 03:10

1 Answers1

0

This is because the code is checking whether the entire string "aa" is contained in specialCharacters, instead of each letter in "aa".