如何检查用户输入字符串的所有字符均属于指定字符列表?
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:
- First, define your allowed characters (using a
setis more efficient for membership checks than a list):allowed_chars = {'w', 'v', 'g'} - Use Python's
all()function to check if every character in the input is in the allowed set. This function returnsTrueonly if all elements in the iterable areTrue. - 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

