python-3.x validation of input().split()

ct3nt3jp  于 2023-10-21  发布在  Python
关注(0)|答案(2)|浏览(116)

我必须使用input().split()来同时输入4个项目,我不知道如何分别验证这4个项目(例如:对于第二项,它必须是十进制和10个字符,或者对于第四项,它必须少于20个字符。有人能帮我一下吗?谢谢你
我自己可以用4个单独的输入()来完成,但不知道如何在一个输入()中完成
my code

name = "0"
identical_num = "wrong"
enterence_year = "wrong"
field= "0"

#name
    
while name.isalpha() == False or len(name)==0 or len(name)>20:
    name= input("Enter the NAME - at least 1 to 20, only character").lower()
        
#identical_num   
    
while True:
    try:
        if len(identical_num)==10 and identical_num.isdecimal():
            break
        else:
            identical_num = input("Enter the IDENTICAL_NUM , must be 10 digit")
    except ValueError:
        print("Invalid input!")
              
#enterence_year 

while True:
   try:
       if enterence_year not in range(1300,1501):
           enterence_year = int(input("Enter the ENTERENCE_YEAR , between 1300 to 1500"))
       else:
           break
                
   except ValueError:
       print("Invalid input!")
            
#field
    
while field.isalpha() == False or len(field)==0 or len(field)>20:
    field= input("Enter the FIELD - at least 1 to 20, only character").lower()
a7qyws3x

a7qyws3x1#

您可以要求用户输入以空格分隔,用空格分隔所有值,然后单独验证每个值。常见的try-except可用于捕获所有ValueError
样本代码:

def validate_name(name):
    if name.isalpha() == False or len(name) == 0 or len(name) > 20:
        raise ValueError("name is at least 1 to 20, only character")

while True:
    # strips extra whitespace on either side of the input
    name, identical_num, enterence_year, field = (
        input("Enter space-separated values: ").strip().split()
    )

    try:
        # validate each field
        validate_name(name)
        # etc ...
        break
    # catch exceptions together
    except ValueError as e:
        print(e)
k4emjkb1

k4emjkb12#

你的代码看起来很好,正如@jarmod评论的那样:
您可以执行以下操作:

name, identical_num, enterence_year, field = input("Enter 4 values separated by a space").split()

从1 input()得到4个值。
继续你的代码。

相关问题