Python中验证用户输入的正确方法

3
我正在学习一些Python教程,其中经常涉及用户输入,我想确认我是否正确验证了它,而不是绕了一个长远的路。
我编写了下面的代码,只需要询问日期、月份和年份,但如果我需要开始询问地址、电话号码、姓名等等,那么这个代码将会变得越来越复杂,这正常吗?
def get_input( i ):

    while True:
        # We are checking the day
        if i == 'd':
            try:
                day = int( raw_input( "Please Enter the day: " ) )
                # If the day is not in range reprint
                if day > 0 and day < 32:
                    #Need to account for short months at some point
                    return day
                else:
                    print 'it has to be between 1 and 31'
            except ( ValueError ):
                print "It has to be a number!"
        elif i == 'm':
            # We are checking the month
            month = raw_input( 'Please enter ' +
                              'in words the month: '
                              ).strip().lower()
            if month in months: # use the dict we created
                return month
            else:
                print 'Please check you spelling!'
        elif i == 'y':
            # Now the year
            try:
                year = int( raw_input( "Please Enter the year" +
                                       "pad with 0's if needed: " ) )
                #make we have enough digits and a positive
                if year > 0 and len( year ) == 4:
                    return year
            except ( ValueError, TypeError ):
                    print "It has to be a four digit number!"

1
最好在http://codereview.stackexchange.com/上询问。 - user647772
代码看起来没问题。根据你想要做什么,可能会有一个验证框架可用。 - kadrian
@esalPsnoroMoN 他/她想知道自己验证用户输入的方式是否正确,这在第一段中已经很明确了。是的,对于那些给这个问题投反对票的人真是可耻。这是怎么回事? - Chetan Kinger
2个回答

5
为什么不让用户一次性输入完整的日期,并尝试验证它?
from time import strptime

def get_date():
    while True:
        date = raw_input("Please enter a date in DD/MM/YYYY format: ")
        try:
            parsed = strptime(date, "%d/%m/%Y")
        except ValueError as e:
            print "Could not parse date: {0}".format(e)
        else:
            return parsed[:3]

year, month, day = get_date()

这将会捕捉到像29/2/2011这样的错误,但是接受像29/2/2012这样的有效输入。
如果您想接受多种格式,只需列出您想要接受的格式字符串列表,并在输入上尝试它们,直到找到一个可用的为止。但是要注意用法过载的问题。
对于验证电话号码,我会选择使用正则表达式。如果您以前从未使用过正则表达式,则此处有一个不错的Python regexp入门指南。地址非常自由,所以我认为除了限制长度和进行基本安全检查外,我不会费心去验证它们,特别是如果您接受国际地址的话。
但是总体而言,如果有一个Python模块可以完成它,您应该尝试根据输入创建一个实例并捕捉错误,就像我在上面的示例中所做的那样。
甚至不要尝试验证姓名。为什么?看看这篇文章。 :)

我只是在寻找缩短我的检查的技巧,因为我觉得我有点过头了。虽然这个练习要求我逐个提示,所以整体检查的想法不适用,但我会记住它的。 - Savo

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接