如何强制用户以特定格式输入?

时间:2020-05-02 21:42:47

标签: python

是否有一种方法可以确保用户输入我希望他们输入的数据, 例如, 我编写了这段代码,以便用户可以输入一些生日,脚本将随机选择一个生日:

import random, re

print("keep in mind that you need to enter the date in this format dd/mm/yyyy")

cont_1 = input("please enter the informations of the 1st contestant : \n")
cont_2 = input("please enter the informations of the 2nd contestant : \n")
cont_3 = input("please enter the informations of the 3rd contestant : \n")
cont_4 = input("please enter the informations of the 4th contestant : \n")
cont_5 = input("please enter the informations of the 5th contestant : \n")

print("Thank you,")

win = cont_1 + " " + cont_2 + " " + cont_3 + " " + cont_4 + " " + cont_5

contDates = re.compile(r'\d\d/\d\d/\d\d\d\d')
ir = contDates.findall(win)
print(" And the Winner is: ", random.choice(ir))

我想知道是否有一种方法可以迫使用户以这种格式.. / .. / ...在输入时输入斜杠,然后输入后两位

3 个答案:

答案 0 :(得分:1)

您可以在不使用正则表达式的情况下检查这种日期格式是否正确。

import datetime
user_input = input()

try:
  datetime.datetime.strptime(user_input,"%d/%m/%Y")
except ValueError as err:
  print('Wrong date format')

答案 1 :(得分:1)

没有简单的方法可以做到这一点。最简单的解决方案是在要求下一个输入之前,先检查用户输入的内容是否正确:

date_re = re.compile(r'\d\d/\d\d/\d\d\d\d')
def ask_date(prompt):
    while True: # Ask forever till the user inputs something correct.
        text = input(prompt)
        if date_re.fullmatch(text): # Does the input match the regex completly (e.g. no trailing input)?
             return text # Just return the text. This will break out of the loop
        else:
             print("Invalid date format. please use dd/mm/yyyy")

cont_1 = ask_date("please enter the informations of the 1st contestant : \n")
cont_2 = ask_date("please enter the informations of the 2nd contestant : \n")
cont_3 = ask_date("please enter the informations of the 3rd contestant : \n")
cont_4 = ask_date("please enter the informations of the 4th contestant : \n")
cont_5 = ask_date("please enter the informations of the 5th contestant : \n")

由于所有日期都有效,因此这也简化了选择过程:

print(" And the Winner is: ", random.choice((cont_1, cont_2, cont_3, cont_4, cont_5))

答案 2 :(得分:-1)

如果要自定义:

i = input("date (dd/mm/yyyy):")
split = i.split("/")
for item in split:
    try:
        int(item)
    except:
        print("error")
        exit()
if len(split) != 3 or len(split[0]) not in [1, 2] or len(split[1]) not in [1, 2] or len(split[2]) != 4:
    print("error!")
else:
    print("accepted!")

这确保所有项目都是数字,并且有3个斜杠,第一个和第二个是两个数字,最后一个是4个数字。如果您想接受任何正确的日期: