You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何检查用户输入字符串的所有字符均属于指定字符列表?

Fixing Multi-Character Validation for Your Word Checker

Got it, let's break down what's going wrong and how to fix this quickly.

Your current code checks if the entire input string exists in the list ['w', 'v', 'g']—which only works when the input is a single character. For multi-character words, the whole string will never match any of those single characters, hence the "no" output even if all characters are allowed.

The Solution: Check Every Character Individually

We need to verify that every character in the input string is part of your allowed list. Here's how to do it cleanly:

  1. First, define your allowed characters (using a set is more efficient for membership checks than a list):
    allowed_chars = {'w', 'v', 'g'}
    
  2. Use Python's all() function to check if every character in the input is in the allowed set. This function returns True only if all elements in the iterable are True.
  3. Update your code like this:
word_input = input("words please: ")  # str() is redundant here, input() returns a string
allowed_chars = {'w', 'v', 'g'}

if all(char in allowed_chars for char in word_input):
    print("yes")
else:
    print("no")

Bonus: Show Which Character Is Invalid

If you want to give more feedback instead of just "no", you can loop through each character and flag the first invalid one:

word_input = input("words please: ")
allowed_chars = {'w', 'v', 'g'}

valid = True
for char in word_input:
    if char not in allowed_chars:
        print(f"no - '{char}' is not allowed")
        valid = False
        break  # Stop checking once we find an invalid character

if valid:
    print("yes")

This way, the user knows exactly what's wrong instead of getting a generic "no".

内容的提问来源于stack exchange,提问作者Mortgage1

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 23:37:50