如果子字符串包含多个字符,Python不会识别它?

2024-10-06 07:05:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图确保word变量不包含禁止字符列表中的字符。这一切似乎都很好,直到我输入了不止一个字符

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

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!"

但是,当字符串包含specialCharacters列表中的两个相同字符时,它返回没有特殊字符,而实际上没有特殊字符。为什么Python不能识别出更多的特殊字符

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!"

Tags: no字符串列表string字符arespecialthere