简体   繁体   English

如何确保用户只能在 Python 中输入某些字符?

[英]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.

相关问题 我需要确保列表中仅某些字符吗? - I need to make sure that only certain characters are in a list? Python如何检查输入是否仅包含某些字符? - Python how to check if an input only contains certain characters? 如何在用户输入末尾检查某些字符? 蟒蛇 - How to check for certain characters at the end of a user input? Python 如何确保我的代码继续循环,同时只接受来自用户输入的整数值? - How can I make sure my code continues to loop while only accepting integer values from the user input? Python如何只接受用户输入的某些单词 - Python How to accept only certain words with user input 在输入 function 中,如何确保用户只输入精确到小数点后 2 位的数字? - In input function, how to make sure the user only enter number with exactly 2 decimals places? 使用 python 列出并仅限制单个字符的输入。如果用户输入两个字符,它将无效 - make a list and limit only the input in single character using python.if the user input two characters it will be invalid 如何在 Python 中将用户输入限制为仅某些整数(即:仅在 1-100 之间,其中还包括 1 和 100) - How can I limit the user input to only certain integers (ie: Only between 1-100, which also includes 1 and 100) in Python Python-检查用户输入以确保它是整数-没有字母等 - Python - Check user input to make sure it is an integer - no letters, etc python,使用if循环来确保用户输入是数字,然后操纵数字 - python, using if loop to make sure user input is a number then manipulate number
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM