如果 Python 包含多个字符,则无法识别子字符串?



我正在努力确保单词变量不包含禁止字符列表中的字符。然而,在我输入多个字符之前,这一切似乎都很好。

例如,这里的代码返回字符串变量中存在预期的特殊字符。

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

if string in specialCharacters:
print("There are special characters!")
else: 
print("No special characters found!")
# This prints "There are special characters!"

但是,当字符串包含specialCharacters列表中的两个相同字符时,它会返回没有特殊字符的事实。为什么Python在有更多特殊字符的情况下不能识别这些字符?

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

if string in specialCharacters:
print("There are special characters!")
else: 
print("No special characters found!")
# This prints "No special characters found!"

这是因为代码正在检查整个字符串"aa";包含在specialCharacters中,而不是"中的每个字母;aa";。

最新更新