我试图确保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!"
这是因为代码正在检查整个字符串“aa”是否包含在特殊字符中,而不是“aa”中的每个字母
相关问题 更多 >
编程相关推荐