[英]How to make sure a user can only input certain characters in Python?
In my program 6 letters will be randomly generated every time and given to the user.在我的程序中,每次都会随机生成 6 个字母并提供给用户。 I want the user to then only be able to input using those 6 letters,and if they don't it will be an error.
我希望用户只能使用这 6 个字母进行输入,否则将是一个错误。 When I try to use a for loop it repeats the code the number of letters the user entered times.
当我尝试使用 for 循环时,它会按照用户输入的字母数重复代码。 When I use regex it only accepts it if it is exactly the same.
当我使用正则表达式时,它只会在完全相同的情况下接受它。 How could I fix this?
我该如何解决这个问题?
Code代码
from random_word import RandomWords
r = RandomWords()
print("WELCOME TO THE ANAGRAM GAME!")
word = r.get_random_word(minLength = 6, maxLength = 6)
print(word)
done = time.time() + 60 * 1
while time.time() < done:
q1 = input("Enter your anagrams")
if re.findall(word, q1):
print("Correct")
answers = []
answers.append(q1)
print(answers)
score = 0
else:
print("Wrong")
Compare the sets of letters:比较字母集:
if set(word) >= set(q1): # Same (or fewer) letters
Operator >=
checks if the right operand is a subset of the left operand.运算符
>=
检查右操作数是否是左操作数的子集。
If you have those random letters in a list:
如果列表中有这些随机字母:
if set(userInput).issubset(set(randomLetters)):
#dosomething
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.