You need to enable JavaScript to run this app. Python如何检测输入字符串中是否存在不在允许字符列表内的字符
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 06:45:09