Python如何检测输入字符串中是否存在不在允许字符列表内的字符
Python代码补全方案
你可以通过集合快速判断字符是否合法,同时对非法字符去重后拼接输出,完整实现代码如下:
allowed_characters = ["a", "b", "c"] # 转换为集合提高字符查找效率 allowed_set = set(allowed_characters) user_input = input("Enter text here: ") # 筛选出所有非法字符,自动去重 invalid_chars = list({char for char in user_input if char not in allowed_set}) if invalid_chars: # 用逗号拼接非法字符输出 print(f"The letter(s) \"{','.join(invalid_chars)}\" is not in the allowed characters list")
实现说明
- 集合的查找效率远高于列表,即使输入长文本也能快速完成校验
- 用集合推导式筛选非法字符时会自动去重,避免同一个非法字符在提示中重复出现
- 输出格式和你给出的示例完全匹配,输入
abcde时会输出The letter(s) "d,e" is not in the allowed characters list
内容的提问来源于stack exchange,提问作者Phantom
相关产品推荐
相关产品推荐

